Java BigDecimal 对象比较:equals() 和 compareTo() 方法
要判断两个 BigDecimal 对象 'a' 和 'b' 是否相等,可以使用 equals() 方法。例如:
BigDecimal a = new BigDecimal('10.00');
BigDecimal b = new BigDecimal('10');
if (a.equals(b)) {
System.out.println('a and b are equal');
} else {
System.out.println('a and b are not equal');
}
在上述代码中,'a' 和 'b' 的值都是 10,但是 'a' 的精度为两位小数,而 'b' 的精度为整数。使用 equals() 方法可以判断两个 BigDecimal 对象的数值是否相等,而不考虑它们的精度。输出结果将是 'a and b are not equal',因为它们的精度不同。
如果要同时考虑数值和精度,可以使用 compareTo() 方法。例如:
if (a.compareTo(b) == 0) {
System.out.println('a and b are equal');
} else {
System.out.println('a and b are not equal');
}
在上述代码中,compareTo() 方法会比较两个 BigDecimal 对象的数值和精度。如果返回值为 0,则表示两个对象相等。输出结果将是 'a and b are equal',因为它们的数值相同且精度也相同。
原文地址: https://www.cveoy.top/t/topic/o6YL 著作权归作者所有。请勿转载和采集!