在bigdecimal的对比大小中,建议使用compare而不是使用equals。
按理说0和0.00应该是相等,但在上图中发现返回结果却是false。
这时候返回结果是true。
接下来是compare的结果:
equals源码:
public boolean equals(Object x) {
if (!(x instanceof BigDecimal))
return false;
BigDecimal xDec = (BigDecimal) x;
if (x == this)
return true;
if (scale != xDec.scale)
return false;
long s = this.intCompact;
long xs = xDec.intCompact;
if (s != INFLATED) {
if (xs == INFLATED)
xs = compactValFor(xDec.intVal);
return xs == s;
} else if (xs != INFLATED)
return xs == compactValFor(this.intVal);
return this.inflate().equals(xDec.inflate());
}
可以发现当小数位scale不等时,自动返回了false。
compare源码:
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;
}
signnum源码:
public int signum() {
return (intCompact != INFLATED)?
Long.signum(intCompact):
intVal.signum();
}
compare源码可见,先对小数位scale进行了对比,如果不等,又将两个数进行了转换,转成int,对比int的大小。