How to compare two BigDecimals in Java.

Home / Java / How to compare two BigDecimals in Java.


This code snippet shows you how to compare a BigDecimal to another in Java.

In order to do this check, we use the compareTo operator of the java.math.BigDecimal class.
The java.math.BigDecimal.compareTo(BigDecimal val) compares a BigDecimal Object with the specified BigDecimal value.

The default usage is

where is one of these six comparison operators: [ <, ==, >, >=, !=, <= ]. x.compareTo(y) returns:

  • 0 if x and y are equal
  • 1 if x is greater than y
  • -1 if x is smaller than y

Ok, lets make some comparisons:

Check if a Java BigDecimal is bigger than another BigDecimal

Check if a Java BigDecimal is smaller than zero

We can use BigDecimal.ZERO to check if a BigDecimal is smaller than zero

Check if a Java BigDecimal is equal to another BigDecimal

Conclusion

In this article we saw how we can use the BigDecimal.compareTo operator to compare a BigDecimal to another one.