Java to C# - intValue() equivalent in c#
I am trying to re-write a piece of code which was in Java to C#, and I ran into a problem, basically I am creating a method which returns a string, but the string returned from c# and java is not the same, therefore the code is fauly. One problem is the following code,
I have this Java Code:
Double localDouble1 = new Double(d1 / 100.0D);
int l = localDouble1.intValue();
And I want to re-write it in C#, I have tried
Double localDouble1 = d1 / 100.0D;
int l = Convert.ToInt32(localDouble1);
It compiles and works, but the result is different, in my particular scenario, the Java int l variable contains 0, and the c# one retur开发者_开发知识库ns 1.
Is there a better method to achieve what I need to do, the same as in Java.
Convert.ToInt32(double) rounds to the nearest integer. intValue()
doesn't - it truncates, just as a cast does (as documented).
Just cast instead:
int l = (int) localDouble1;
(Also try to avoid names like l
which look like 1
:)
Try this.
Double localDouble1 = d1 / 100.0D;
int l=Convert.ToInt32(Math.Floor(localDouble1));
Because Convert.ToInt32 If value is halfway between two whole numbers, the even number is returned; that is, 5.5 is converted to 6, and 6.5 is converted to 7. Explicit numeric conversions table
cast int l = (int) localDouble1;
精彩评论