Why BigDecimal("5.50") not equals to BigDecimal("5.5") and how to work around this issue?

Roman picture Roman · Oct 5, 2010 · Viewed 37.5k times · Source

Actually, I've found possible solution

//returns true
new BigDecimal("5.50").doubleValue() == new BigDecimal("5.5").doubleValue()

Of course, it can be improved with something like Math.abs (v1 - v2) < EPS to make the comparison more robust, but the question is whether this technique acceptable or is there a better solution?

If someone knows why java designers decided to implement BigDecimal's equals in that way, it would be interesting to read.

Answer

Colin Hebert picture Colin Hebert · Oct 5, 2010

From the javadoc of BigDecimal

equals

public boolean equals(Object x)

Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

Simply use compareTo() == 0