Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java to C# - intValue() equivalent in c#

Tags:

java

c#

asp.net

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 returns 1.

Is there a better method to achieve what I need to do, the same as in Java.

like image 721
Ryan S Avatar asked Jan 16 '26 23:01

Ryan S


1 Answers

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 :)

like image 166
Jon Skeet Avatar answered Jan 19 '26 12:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!