Monday, June 25, 2012

BigDecimal equals ZERO

So I've read that .equals() may not always work on a BigDecimal value, and that I should use .compareTo() instead, but I guess I never really believed it before, until today.

package sandbox;
import java.math.BigDecimal;
public class BigDecimalEqualsCompareTo {

    public static void main(String[] args) {
        
        BigDecimal x = BigDecimal.ZERO;
        BigDecimal y = BigDecimal.valueOf((double) 0);
        
        x = x.add(y);

        if (x.equals(BigDecimal.ZERO)) {
            System.out.println(".equals worked!");
        }
        else {
            System.out.println(".equals FAILED!");
        }
        
        if (x.compareTo(BigDecimal.ZERO) == 0) {
            System.out.println(".compareTo worked!");
        }
        else {
            System.out.println(".compareTo FAILED!");
        }
        
    }
    
}

run:
.equals FAILED!
.compareTo worked!
.
The above code demonstrates one instance in which .compareTo will work when .equals will fail.
.
The value of y is "0.0" where BigDecimal.ZERO is actually "0", which you and I both know is the same number but because the scale of y is now 1, y is considered a different BigDecmal than ZERO. If you set the scale of both variables to the same, then .equals will work again, but at that point isn't easier to simply use .compareTo?

No comments:

Post a Comment