Video in progress

Strong Junior ☕ Core Java

Why does new BigDecimal("2.0").equals(new BigDecimal("2.00")) return false?

BigDecimal.equals compares the scale (the number of digits in the fractional part) along with the value: 2.0 (scale 1) and 2.00 (scale 2) are not equal. To compare only the numeric value, use compareTo(...) == 0.

📖 Answer

BigDecimal a = new BigDecimal("2.0");
BigDecimal b = new BigDecimal("2.00");

a.equals(b);          // false
a.compareTo(b) == 0;  // true

Where this causes trouble:

  • in a test, assertEquals(new BigDecimal("100"), total) fails if total is 100.00. In AssertJ, use isEqualByComparingTo.
  • as a HashSet<BigDecimal> element or a HashMap key, 2.0 and 2.00 become two different entries.
  • a value read from the DB as NUMERIC(12,2) always has scale 2, while the one created in code has a different one.

What to do:

  • always use compareTo for comparison;
  • before using one as a key, make the scale the same: value.setScale(2, RoundingMode.HALF_UP);
  • or stripTrailingZeros() (but 100 can become 1E+2, so use toPlainString() for output).

A handy way for money is to write a Money value object and always keep the scale the same inside it.