Why Not double for Money
Floating-point precision problems.
A Dangerous Default
It feels natural to store prices in a double. Unfortunately double cannot represent most decimal fractions exactly, which leads to tiny errors that ruin financial calculations.
The Classic Surprise
Add 0.1 and 0.2 with double and you do not get 0.3. You get a value with a tiny rounding error.
public class Main {
public static void main(String[] args) {
double result = 0.1 + 0.2;
System.out.println(result);
}
}All lessons in this course
- Why Not double for Money
- Working with BigDecimal
- Rounding and Scale
- BigInteger for Huge Numbers