Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sum of all double does not return expected result [duplicate]

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?

like image 732
Jack Avatar asked Nov 28 '22 14:11

Jack


1 Answers

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

like image 196
partlov Avatar answered Dec 09 '22 09:12

partlov