I've just recently come across a behavior inside BigDecimal
that I wasn't previously aware of. I've always used them as an alternative to double for areas where precision is important. For example in financial calculations.
However I recently came across this fact
new BigDecimal("1.0").equals(new BigDecimal("1")) == false
I have to admit I was surprised by this. I figure it is because the first has a scale of 1 while the second has a scale of 0, but still it seems counter-intuitive. I think the reason I've never run into it before is because we've always used fixed scale BigDecimals
for financial calculations.
Checking the BigDecimal
documentation I can see that says that compareTo() == 0
should be used to check for equality ignoring scale while that equals()
compares both the value and the scale.
Are there any other similar gotchas I should be aware of when using BigDecimal
s with different scales?