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
1 |
x.compareTo(y) <op> 0 |
where 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
1 2 3 4 5 |
BigDecimal smallBigDecimal = new BigDecimal(1); BigDecimal bigBigDecimal = new BigDecimal(1000); if ( smallBigDecimal.compareTo(bigBigDecimal) < 0 ){ System.out.println("Yep, " + smallBigDecimal+ " is smaller than " +bigBigDecimal+ "!"); } |
Check if a Java BigDecimal is smaller than zero
We can use BigDecimal.ZERO
to check if a BigDecimal is smaller than zero
1 2 3 4 |
BigDecimal myBigDecimal = new BigDecimal(-1); if ( myBigDecimal.compareTo(BigDecimal.ZERO) < 0 ){ System.out.println("Yep, " + myBigDecimal + " is smaller than zero!"); } |
Check if a Java BigDecimal is equal to another BigDecimal
1 2 3 4 5 |
BigDecimal bigDecimal1 = new BigDecimal(1000); BigDecimal bigDecimal2 = new BigDecimal(1000); if ( bigDecimal1.compareTo(bigDecimal2) == 0 ){ System.out.println("Yep, " + bigDecimal1+ " is equal to " +bigDecimal2+ "!"); } |
Conclusion
In this article we saw how we can use the BigDecimal.compareTo
operator to compare a BigDecimal to another one.