Search code examples
javaequalsbigdecimalcompareto

BigDecimal equals() versus compareTo()


Consider the simple test class:

import java.math.BigDecimal;

/**
 * @author The Elite Gentleman
 *
 */
public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BigDecimal x = new BigDecimal("1");
        BigDecimal y = new BigDecimal("1.00");
        System.out.println(x.equals(y));
        System.out.println(x.compareTo(y) == 0 ? "true": "false");
    }

}

You can (consciously) say that x is equal to y (not object reference), but when you run the program, the following result shows:

false
true

Question: What's the difference between compareTo() and equals() in BigDecimal that compareTo can determine that x is equal to y?

PS: I see that BigDecimal has an inflate() method on equals() method. What does inflate() do actually?


Solution

  • The answer is in the JavaDoc of the equals() method:

    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).

    In other words: equals() checks if the BigDecimal objects are exactly the same in every aspect. compareTo() "only" compares their numeric value.

    As to why equals() behaves this way, this has been answered in this SO question.