Wednesday, February 10, 2010

Java: Comparing BigDecimal objects for equality

If you are developing a financial application you would probably agree that 1.0 is equivalent to 1.00, but the BigDecimal API says otherwise. If you will run the following code, you will be bewildered at first on the results:
package blogspot.soadev.test;
import java.math.BigDecimal;
public class BigDecimalTestRunner {
    public static void main(String[] args) {
        BigDecimal x = new BigDecimal("1.0");
        BigDecimal y = new BigDecimal("1.00");
        System.out.println(x.equals(y));
        System.out.println(x.compareTo(y) == 0);
    }
}
The result:
false
true
Some excerpts from the BigDecimal JavaDocs:

equals
public boolean equals(Object x)
Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimals equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
Overrides:
equals in class Object
Parameters:
x - Object to which this BigDecimal is to be compared.
Returns:
true if and only if the specified Object is a BigDecimal whose value and scale are equal to this BigDecimal's.

compareTo
public int compareTo(BigDecimal val)
Compares this BigDecimal with the specified BigDecimal. Two BigDecimals that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.
Parameters:
val - BigDecimal to which this BigDecimal is to be compared.
Returns:
-1, 0 or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

So therefore, the next time you will check the BigDecimal objects for equality in the financial context, use compareTo() instead of equals().

No comments:

Post a Comment