Video in progress
Why do you use BigDecimal and not double when calculating with money?
A double is stored in binary and can't represent decimal fractions like 0.1 exactly, so rounding errors pile up. BigDecimal stores the decimal number exactly, and you set the rounding rule yourself.
📖 Answer
System.out.println(0.1 + 0.2); // 0.30000000000000004
System.out.println(1.10 - 1.00); // 0.10000000000000009
Over a million transactions these errors turn into cents, and then into whole dollars.
With BigDecimal:
BigDecimal price = new BigDecimal("19.99"); // from a String!
BigDecimal qty = BigDecimal.valueOf(3);
BigDecimal total = price.multiply(qty); // 59.97
BigDecimal vat = total.multiply(new BigDecimal("0.12"))
.setScale(2, RoundingMode.HALF_UP);
The traps:
new BigDecimal(0.1)takes the inexact value of the double (0.1000000000000000055...). Usenew BigDecimal("0.1")orBigDecimal.valueOf(0.1).- in division, if the result is an infinite fraction (
1/3),dividethrows an exception: give it a scale and aRoundingMode.
Another way is to store the amount in the smallest unit (cents) as a long. It's fast and exact, but for percentages and exchange rates you still have to think about rounding.
Sign up to mark studied questions and save your progress.