user3139293 user3139293 - 4 months ago 12
Java Question

Strange behavior of double data type

My code is as follows:

Number inputAmount = NumberFormat.getNumberInstance(Locale.FRANCE).parse("7,10");
double doubleValue = inputAmount.doubleValue();
int intValue = (int) (doubleValue * 100);

System.out.println("Input: " + inputAmount);
System.out.println("Double: " + doubleValue);
System.out.println("Integer: " + intValue);


which outputs:

Input: 7.1
Double: 7.1
Integer: 710


But, when the
inputValue
is 5,10 the output is:

Input: 5.1
Double: 5.1
Integer: 509


This happens only with 5,10 and 4,10. I know that it happens due to the double precision but I cannot figure out exactly how.
Any ideas?

Answer

The problem here is, that the multiplication 5.1d * 100d produces a rounding error, that results in 509.99999999999994d. And when you cast this double into an integer, then the result is obviously 509.

To understand what is going on here, consider the following:

double doubleValue = 5.1d * 100d; // rounding error...
System.out.println("Double: " + doubleValue);
int intValue = (int) doubleValue;
System.out.println("Integer: " + intValue);

Output:

Double: 509.99999999999994
Integer: 509