What is the method for comparing BigDecimals in Java?
In Java, the compareTo() method can be used to compare the size of two BigDecimal objects. This method returns an integer value indicating the relationship between the two BigDecimal objects. The specific rules are as follows:
- Return a negative number if the first BigDecimal object is less than the second BigDecimal object.
- Return a positive number if the first BigDecimal object is greater than the second BigDecimal object.
- If two BigDecimal objects are equal, return 0.
The sample code is shown below:
BigDecimal num1 = new BigDecimal("10");
BigDecimal num2 = new BigDecimal("5");
int result = num1.compareTo(num2);
if (result > 0) {
System.out.println("num1 is greater than num2");
} else if (result < 0) {
System.out.println("num1 is less than num2");
} else {
System.out.println("num1 is equal to num2");
}