Last Updated: February 25, 2016
· dcshock

BigDecimal .equals scale comparison

I ran into an issue this morning with the java BigDecimal equals implementation. When comparing the two BigDecimal objects

BigDecimal one = new BigDecimal(1);
BigDecimal two = new BigDecimal(1.0);

they do not equal using .equals().

one.equals(two) == false

There are benefits of doing the comparison this way since the number of decimal places are considered. However, in some cases code is just being converted from double/Double to BigDecimal. In those scenarios the way to consider the objects equal by value is to use the .compareTo() method.

boolean equal = one.compareTo(two) == 0;