I found out that I cannot use floating point types (float / double in Java) to calculate cash
You cannot use double to accurately represent money worth more than $ 70 trillion. For values ββless than this, you can use double or long without errors (provided that you use the appropriate rounding)
IMHO using double easier to work with if you understand the need for rounding.
However, many believe that his error is subject to esp, because you do not know who might need to maintain the code. Using BigDecimal will ensure proper rounding and give you several options for how this works.
Many people think that even 0.1 does not represent exactly, and BigDecimal can display the exact representation (and why you should be careful with how you convert to BigDecimal)
System.out.println(new BigDecimal(0.1));
prints
0.1000000000000000055511151231257827021181583404541015625
Many use inefficiently
new BigDecimal(Double.toString(0.1))
or the like, which works, but ironically, itβs as accurate as the toString method, which they are trying to avoid.
A more efficient way to do this:
BigDecimal.valueOf(0.1)
This avoids the need to create a string.
Libraries supporting double will correctly display this number, but once you do the calculation, the default round may not be enough.
System.out.println(0.1 * 3);
prints
0.30000000000000004
In this situation, you must say what accuracy you expect. Say you have a dollar and cents that you can use
System.out.printf("%.2f%n", 0.1 * 3);
prints
0.30
To find where you can no longer add 0.01
for (double d = 1; d < Long.MAX_VALUE; d *= 2) { long l = Double.doubleToLongBits(d); double d1 = Double.longBitsToDouble(l + 1); if (d1 - d > 0.01) { System.out.println("Cannot represent " + d + " plus 0.01"); double d_1 = Double.longBitsToDouble(l - 1); if (d - d_1 < 0.01) System.out.println("Can represent " + d + " minus 0.01"); break; } }
prints
Cannot represent 7.0368744177664E13 plus 0.01 Can represent 7.0368744177664E13 minus 0.01