views:

1279

answers:

3

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!

+6  A: 

Java rounds toward zero when narrowing from a floating point to an integer type.

There's more documentation about the general rules in the Java Language Specification. Note that while the documentation in Number leaves options open for subclasses, the documentation on the concrete boxing types is more explicit:

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.

erickson
+11  A: 
Jon Skeet
+3  A: 

Jon Skeet is correct, but something else to watch for is that .NET uses Banker's Rounding as its rounding algorithm. When you're halfway between round towards the even integer.

Lee
Actually, it's even worse than that. .NET uses banker's rounding in most situations, but not all (format strings are one case where common rounding is used). You also have the ability to change the rounding method used in .NET 2.0 and later.
Scott Dorman