Java Compare two BigDecimal values
Tags: BigDecimal
In this Java core tutorial we learn how to compare two BigDecimal values in Java programming language using the BigDecimal.compareTo() method.
How to compare BigDecimal values in Java
In Java, to compare two BigDecimal values we can use the compareTo() method which return value of -1, 0 or 1 if the value is less than, equal to, or greater than the value it compare to.
The following Java example to show you the compareTo() method return 1 when the value is greater than the value it compare to.
BigDecimalCompareToExample1.java
import java.math.BigDecimal;
public class BigDecimalCompareToExample1 {
public static void main(String... args) {
BigDecimal bigDecimal1 = new BigDecimal(2000);
BigDecimal bigDecimal2 = new BigDecimal(1000);
int compareResult = bigDecimal1.compareTo(bigDecimal2);
System.out.println(compareResult);
}
}
1
The following Java example to show you the compareTo() method return -1 when the value is less than the value it compare to.
BigDecimalCompareToExample2.java
import java.math.BigDecimal;
public class BigDecimalCompareToExample2 {
public static void main(String... args) {
BigDecimal bigDecimal1 = new BigDecimal(1000);
BigDecimal bigDecimal2 = new BigDecimal(2000);
int compareResult = bigDecimal1.compareTo(bigDecimal2);
System.out.println(compareResult);
}
}
-1
The following Java example to show you the compareTo() method return 0 when the value is equal to the value it compare to.
BigDecimalCompareToExample3.java
import java.math.BigDecimal;
public class BigDecimalCompareToExample3 {
public static void main(String... args) {
BigDecimal bigDecimal1 = new BigDecimal(2000);
BigDecimal bigDecimal2 = new BigDecimal(2000);
int compareResult = bigDecimal1.compareTo(bigDecimal2);
System.out.println(compareResult);
}
}
0
Happy Coding 😊