Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different answer when converting a Double to an Int - Java vs .Net

In C# if I want to convert a double (1.71472) to an int then I get the answer 2. If I do this in Java using intValue() method, I get 1 as the answer.

Does Java round down on conversions?

Why do the Java API docs have such scant information about their classes i.e.

Returns the value of the specified number as an int. This may involve rounding or truncation.

A bit more info about the rounding would have been helpful!

like image 410
Vidar Avatar asked Nov 29 '22 21:11

Vidar


1 Answers

Java rounds toward zero when narrowing from a floating point to an integer type—and so does C#, when you use the casting conversion. It's Convert.ToInt32 that rounds:

double d = 1.71472;
int x = (int) d; // x = 1
int y = Convert.ToInt32(d); // y = 2

Details can be found in the Java Language Specification. Note that while the documentation cited in Number leaves options open for subclasses, the documentation on the concrete boxing types, like Double, is explicit about the implementation:

Returns the value of this Double as an int (by casting to type int).

When using BigDecimal, you can specify one of eight different rounding policies.

like image 149
Jon Skeet Avatar answered Dec 05 '22 18:12

Jon Skeet