有个是否为零的判断【BigDecimal.ZERO.equals(ratio)】我用了BigDecimal的equals方法,结果,判断失败,因此特地分析一下equals与compareTo的区别。本文参考JAVA_VERSION="1.7.0"。首先看一下BigDecimal的equals方法源码:
public int compareTo(BigDecimal val) {
// Quick path for equal scale and non-inflated case.
if (scale == val.scale) {
long xs = intCompact;
long ys = val.intCompact;
if (xs != INFLATED && ys != INFLATED)
return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
}
int xsign = this.signum();
int ysign = val.signum();
if (xsign != ysign)
return (xsign > ysign) ? 1 : -1;
if (xsign == 0)
return 0;
int cmp = compareMagnitude(val);
return (xsign > 0) ? cmp : -cmp;
}
可以看到BigDecimal的equals方法是先判断数据类型,在数据类型一致的前提下再判断精确度(scale)和值(BigInteger的equals方法)是否一致。
其实javadoc里面就已经写的很明白:“Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).”只是自己没有去注意罢了!再看一下compareTo方法源码:
public int compareTo(BigDecimal val) {
// Quick path for equal scale and non-inflated case.
if (scale == val.scale) {
long xs = intCompact;
long ys = val.intCompact;
if (xs != INFLATED && ys != INFLATED)
return xs != ys ? ((xs > ys) ? 1 : -1) : 0;
}
int xsign = this.signum();
int ysign = val.signum();
if (xsign != ysign)
return (xsign > ysign) ? 1 : -1;
if (xsign == 0)
return 0;
int cmp = compareMagnitude(val);
return (xsign > 0) ? cmp : -cmp;
}
可以看到这个方法里面有个compareMagnitude的处理,把val转换为int,然后再进行比较,这里省略compareMagnitude的实现。
signum()方法,返回该数值的正负号,正数,0,负数分别对应返回结果:1,0,-1;举个栗子:
BigDecimal ratio = new BigDecimal("0.00");
if (0 == BigDecimal.ZERO.compareTo(ratio)) {
System.out.println("二者相等");
} if (!BigDecimal.ZERO.equals(ratio)) {
System.out.println(" 居然不相等 ");
}
结论:对于BigDecimal的大小比较,equals方法不仅比较值的大小,还比较两个对象的精确度,而compareTo方法则不比较精确度,只比较数值的大小。