Java Dailly Tip: How to use comparison operators like >, =, < on BigDecimal

Java Dailly Tip: How to use comparison operators like >, =, < on BigDecimal

Problem

I have a domain class with unitPrice set as BigDecimal data type. Now I am trying to create a method to compare price but it seems like I can't have comparison operators in BigDecimal data type. Do I have to change data type or is there other way around?

Solution

Here is an example for all six boolean comparison operators (<, ==, >, >=, !=, <=):

BigDecimal big10 = new BigDecimal(10);
BigDecimal big20 = new BigDecimal(20);

System.out.println(big10.compareTo(big20) < -1);  // false
System.out.println(big10.compareTo(big20) <= -1); // true
System.out.println(big10.compareTo(big20) == -1); // true
System.out.println(big10.compareTo(big20) >= -1); // true
System.out.println(big10.compareTo(big20) > -1);  // false
System.out.println(big10.compareTo(big20) != -1); // false

System.out.println(big10.compareTo(big20) < 0);   // true
System.out.println(big10.compareTo(big20) <= 0);  // true
System.out.println(big10.compareTo(big20) == 0);  // false
System.out.println(big10.compareTo(big20) >= 0);  // false
System.out.println(big10.compareTo(big20) > 0);   // false
System.out.println(big10.compareTo(big20) != 0);  // true

System.out.println(big10.compareTo(big20) < 1);   // true
System.out.println(big10.compareTo(big20) <= 1);  // true
System.out.println(big10.compareTo(big20) == 1);  // false
System.out.println(big10.compareTo(big20) >= 1);  // false
System.out.println(big10.compareTo(big20) > 1);   // false
System.out.println(big10.compareTo(big20) != 1);  // true

Also You can follow this utility static method and Operator enum for comparing the two numbers:

public static boolean check(BigDecimal firstNum, Operator operator, BigDecimal secondNum) {
    switch (operator) {
        case EQUALS:
            return firstNum.compareTo(secondNum) == 0;
        case LESS_THAN:
            return firstNum.compareTo(secondNum) < 0;
        case LESS_THAN_OR_EQUALS:
            return firstNum.compareTo(secondNum) <= 0;
        case GREATER_THAN:
            return firstNum.compareTo(secondNum) > 0;
        case GREATER_THAN_OR_EQUALS:
            return firstNum.compareTo(secondNum) >= 0;
    }

    throw new IllegalArgumentException("Will never reach here");
}

public enum Operator {
    LESS_THAN, LESS_THAN_OR_EQUALS, GREATER_THAN, GREATER_THAN_OR_EQUALS, EQUALS
}

Share this Post