BigDecimal类提供了多个方法可以用来比较两个BigDecimal对象的大小。以下是一些常用的方法:
示例:
BigDecimal num1 = new BigDecimal("10");
BigDecimal num2 = new BigDecimal("20");
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 greater than num2");
} else {
System.out.println("num1 is equal to num2");
}
示例:
BigDecimal num1 = new BigDecimal("10");
BigDecimal num2 = new BigDecimal("10");
if (num1.equals(num2)) {
System.out.println("num1 is equal to num2");
} else {
System.out.println("num1 is not equal to num2");
}
示例:
BigDecimal num1 = new BigDecimal("10.123");
BigDecimal num2 = new BigDecimal("10.124");
MathContext mc = new MathContext(2, RoundingMode.HALF_UP);
int result = num1.compareTo(num2, mc);
if (result < 0) {
System.out.println("num1 is less than num2");
} else if (result > 0) {
System.out.println("num1 is greater than num2");
} else {
System.out.println("num1 is equal to num2");
}
通过以上方法,可以方便地比较两个BigDecimal对象的大小。