Search code examples
javabigdecimal

BigDecimal#compareTo with different scales


Why does the following return 1?

new BigDecimal(0.82).setScale(5, BigDecimal.ROUND_HALF_DOWN)
    .compareTo(new BigDecimal(0.82))

I expect this to return 0 because BigDecimal.compareTo ignores scale according to its documentation:

Compares this BigDecimal with the specified BigDecimal. Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. [...]


Solution

  • new BigDecimal(0.82) is not actually 0.82, because you're passing a double value -- the double closest to 0.82, which is not exactly 0.82 -- to the constructor, so new BigDecimal(0.82) is a BigDecimal equal to the double closest to 0.82.

    Instead, use new BigDecimal("0.82").