Recently, I came across behavior inside BigDecimal that I did not know about before. I have always used them as an alternative to the double for areas where precision is important. For example, in financial calculations.
However, I recently encountered this fact.
new BigDecimal("1.0").equals(new BigDecimal("1")) == false
I must admit that I was surprised by this. I believe this is because the first has a scale of 1, and the second has a scale of 0, but still it seems contrary to intuition. I think the reason I have never come across this before is because we always used the fixed scale of BigDecimals for financial calculations.
Checking the BigDecimal documentation I can see that it says that compareTo() == 0 should be used to check for equality ignoring scale, while equals() compares value and scale.
Are there any other similar errors that I should know about when using BigDecimal with different scales?
Tim b source share