BigDecimal equals might not be what you expect

import java.math.BigDecimal;
 
public class BigDecimalTest
{
    public static void main(String[] args)
    {
        BigDecimal a = new BigDecimal("0");
        BigDecimal b = new BigDecimal("0.0");
        System.out.println(a.equals(b)); // => false
        System.out.println(a.compareTo(b) == 0); // => true
    }
}

BigDecimal in Java poses a small trap for the unwary, because its equals method doesn’t work how you might expect. Two BigDecimals are only equal if they have the same value and the same scale. As my little example illustrates, it is possible to have two BigDecimals with the same numerical value that don’t compare as equals.

The correct way to compare two BigDecimals for equality when you only care about the overall numerical value, is to use the compareTo method.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*