views:

190

answers:

2

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.

+16  A: 

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

Colin Hebert
+3  A: 

call setScale to the same thing on the numbers you're comparing:

new BigDecimal ("5.50").setScale(2).equals(new BigDecimal("5.5").setScale (2))
Nathan Hughes
only do this if you want to consider "5.051" == "5.05" as the setScale(2) will drop that extra digit, where as .compareTo(other) will compare the values without regard to scale
Gareth Davis
Gareth, `setScale` without a rounding mode parameter will not drop the extra digits, instead it will throw an ArithmeticException. So this would only work if the extra digits are all zeroes.
Jörn Horstmann
Don't you need to use equals() here? If you use == you are comparing the object references, not the values.
teto
@teto: that sounds right, i edited to use your suggestion
Nathan Hughes