BigDecimal是java.math包中提供的API类
#####代码展示#####
public class Test {
public static void main(String[] args) throws Exception {
BigDecimal a = new BigDecimal("0");
BigDecimal b = new BigDecimal("0.00");
BigDecimal c = new BigDecimal("0");
System.out.println(a.equals(b)); //false
System.out.println(a.equals(c)); //true
System.out.println(a.compareTo(b)==0); //true
}
}
BigDecimal类型的数据比较大小时应该使用compareTo方法
如果方法的调用方的值大于方法中参数值,即a>b,方法的返回结果是1;
如果方法的调用方的值小于方法中参数值,即a<b,方法的返回结果是-1;
如果方法的调用方的值等于方法中参数值,即a=b,方法的返回结果是0;
####BigDecimal类中的compareTo方法######
public int compareTo(BigDecimal val) {
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方法#####
@Override
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.inflated().equals(xDec.inflated());
}
BigDecimal类型的数据比较应使用compareTo方法,不应使用equal方法