How to compare two numbers in Java using BigDecimal?
In Java, we can compare the size of two BigDecimal objects using the compareTo() method of the BigDecimal class.
The return value of the compareTo() method is an integer that indicates the relationship in size between two BigDecimal objects. The specific meanings of the return values are as follows:
- A negative integer will be returned if the current object is less than the target object.
- If the current object is equal to the target object, then return 0.
- Return a positive integer if the current object is greater than the target object.
Here is an example code comparing the sizes of two BigDecimal objects.
import java.math.BigDecimal;
public class BigDecimalComparisonExample {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("10.5");
BigDecimal num2 = new BigDecimal("5.7");
int result = num1.compareTo(num2);
if (result < 0) {
System.out.println("num1 is less than num2");
} else if (result == 0) {
System.out.println("num1 is equal to num2");
} else {
System.out.println("num1 is greater than num2");
}
}
}
In the example above, we compared num1 and num2 using the compareTo() method, and based on the return value, we determined their size relationship. The output result is “num1 is greater than num2,” indicating that num1 is bigger than num2.