Java 将不同类型的对象视为不同的对象。这意味着即使它们代表了等价的东西,它们也不相同。
BigDecimal 的“特别”之处在于,即使类型相同且值相等,但具有不同的比例尺,它们仍然不“等于”
Double d = 0.0;
Integer i = 0;
System.out.println(d + " equals " + i + " is " + (d.equals(i)));
BigDecimal bd2 = new BigDecimal("0.00");
BigDecimal bd3 = new BigDecimal("0.000");
System.out.println(bd2 + " equals " + d + " is " + (bd2.equals(d)));
System.out.println(bd2 + " equals " + bd2 + " is " + (bd2.equals(bd2)));
System.out.println(bd2 + " equals " + bd3 + " is " + (bd2.equals(bd3)));
印刷
0.0 equals 0 is false
0.00 equals 0.0 is false
0.00 equals 0.00 is true
0.00 equals 0.000 is false
解决这个问题的方法是使用 compareTo 来调整比例并为您提供更自然的比较。
System.out.println(bd2 + " compareTo " + BigDecimal.ZERO + " is " + (bd2.compareTo(BigDecimal.ZERO )));
System.out.println(bd3 + " compareTo " + BigDecimal.ZERO + " is " + (bd3.compareTo(BigDecimal.ZERO )));
印刷
0.00 compareTo 0 is 0
0.000 compareTo 0 is 0
这意味着如果您要使用 BigDecimal,您需要编写
if(value1.compareTo(BigDecimal.ZERO) != 0 && value2.compareTo(BigDecimal.ZERO) != 0) {
就个人而言,我更喜欢使用double
更简单、更快的方法。唯一的缺点是您必须自己管理舍入。
double div = value1 / value2;
if (0 < div && div < SOME_UPPER_SENSIBLE_LIMIT) {
// division was ok.
System.out.printf("%.4f", div); // print with rounding.