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 specifiedBigDecimal
. TwoBigDecimal
objects that are equal in value but have a different scale (like2.0
and2.00
) are considered equal by this method. [...]
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")
.