Video in progress
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 iftotalis100.00. In AssertJ, useisEqualByComparingTo. - as a
HashSet<BigDecimal>element or aHashMapkey,2.0and2.00become 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
compareTofor comparison; - before using one as a key, make the scale the same:
value.setScale(2, RoundingMode.HALF_UP); - or
stripTrailingZeros()(but100can become1E+2, so usetoPlainString()for output).
A handy way for money is to write a Money value object and always keep the scale the same inside it.
Sign up to mark studied questions and save your progress.