Why is 0.1 + 0.2 != 0.3, and why not use double for money? How do you use BigDecimal correctly?
Short answer
double is stored in binary, and 0.1 cannot be written exactly in binary, so 0.1 + 0.2 gives 0.30000000000000004. Money uses BigDecimal built from a string.
3 points to say:
- Create it with
new BigDecimal("0.1"), never from adouble. dividealways takes a scale and a rounding mode.- Compare with
compareTo:equalstreats2.0and2.00as different.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.