SteelReed

Search

Search posts, questions…

Java CoreQuestion 12 / 43

Middle

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.

0.1 repeats forever in base 2divide with scale,RoundingMode0.1 + 0.2 as double0.30000000000000004Need to handle moneyBigDecimal from Stringlong in centsCompare with compareTo

3 points to say:

  1. Create it with new BigDecimal("0.1"), never from a double.
  2. divide always takes a scale and a rounding mode.
  3. Compare with compareTo: equals treats 2.0 and 2.00 as 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.