Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

try changing:

int intValue = (int) (doubleValue * 100);

to:

int intValue = (int) (doubleValue * 100d);

Your code is fairly simplified already, I'm thinking something weird might be going on with the internal casting when it multiplies. 100d will force it to multiply two doubles before final conversion to int.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top