I want to do the following calculation:
615.6555 + 566
I expected this result:
1181.6555
However, this is returning this:
1181.6554999999998
How do I solve this problem?
I want to do the following calculation:
615.6555 + 566
I expected this result:
1181.6555
However, this is returning this:
1181.6554999999998
How do I solve this problem?
For mathematical calculations always use BigDecimal. BigDecimal is a class that works with arbitrary precision floating-point numbers, which pick you how much accuracy you want to use. But here's an interesting catch here if you use BigDecimal like this:
BigDecimal b1 = new BigDecimal(615.6555);
BigDecimal b2 = new BigDecimal(566);
System.out.println(b1.add(b2));
You will receive the same unexpected result. The documentation itself provides this possibility: "This builder's results may be unpredictable ". You have two solutions to deal with this problem, according to the documentation itself, the first would be to use String:
BigDecimal b1 = new BigDecimal(Double.toString(615.6555));
And second, if you want to keep the double instead of converting it, use the static valueOf method:
BigDecimal b1 = BigDecimal.valueOf(615.6555);
For accounts with a large number of decimal places, it may be interesting to use the
java.math.BigDecimal
So, the account would look like this:
BigDecimal valor1 = new BigDecimal("615.6555");
BigDecimal valor2 = new BigDecimal("566");
BigDecimal soma = valor1.add(valor2);
System.out.println(soma); // Imprime 1181.6555
In addition, with this class you can easily control the precision of the tithe values with the setScale method, and of course, in addition to other arithmetic operations. Here's a practical, didactic example: