Java sum of all double does not return expected result

Jack picture Jack · Jan 8, 2013 · Viewed 25.9k times · Source

Possible Duplicate:
Moving decimal places over in a double

Why is the following sum of numbers not equal to 0.4622? but 0.46219999999999994

Double total = new Double(0.08) + new Double(0.0491) + new Double(0.3218) + 
         new Double(0.0113) + new Double(0.0); // = 0.46219999999999994

I have an application that checks the users input.

The user inputs 5 decimal numbers and a total number. The application checks if the sum of all 5 numbers capped at 4 decimals behind the komma is equal to the total number.

Capping it gives me 0.4621 which is not equal to 0.4622. I can't use DecimalFormat because it rounds it up. And if i explicitly say, round down then it will fail for this situation.

Any suggestion for how I can solve this?

Answer

partlov picture partlov · Jan 8, 2013

Try with java.math.BigDecimal. Double rounds result. You will just have to use add method, not + operator.