概述
在项目中使用BigDecimal的equals方法比较大小时,结果不为true,直接上示例
public static void main(String[] args) {
BigDecimal a = new BigDecimal(0.00);
BigDecimal b = new BigDecimal(0);
boolean result = a.equals(b);
System.out.println("a equals b -->" + result);
BigDecimal c = new BigDecimal("0.00");
BigDecimal d = new BigDecimal("0");
boolean result1 = c.equals(d);
System.out.println("c equals d -->" + result1);
}
结果:
a equals b -->true
c equals d -->false
可以看到a和b比较结果是true,c和d比较的结果为fasle
c、d使用传入字符串的构造器(等同于数据库查询出来的值)
项目中从数据库查询出来的值进行比较时(上例中c、d)显然不是我们期望的结果,因此修改为如下方法
boolean result2 = c.compareTo(d) == 0;
System.out.println("c compareTo d -->" + result2);
结果:
c compareTo d -->true
我们来看下构造器:
public BigDecimal(String val) {
this(val.toCharArray(), 0, val.length());
}
该构造器的注释:
可以看出,“0”传入构造器得到的是0且没有小数位,“0.00”传入构造器得到的是0.00,含有2位小数
再看看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());
}
可以清晰看到equals方法比较了小数位数 -----> if (scale != xDec.scale) return false;
到这里可以理解上面C、Dequals比较结果为什么是false了
再来看看compareTo方法
/**
* Compares this {@code BigDecimal} with the specified
* {@code BigDecimal}. Two {@code BigDecimal} objects that are
* equal in value but have a different scale (like 2.0 and 2.00)
* are considered equal by this method. This method is provided
* in preference to individual methods for each of the six boolean
* comparison operators ({@literal <}, ==,
* {@literal >}, {@literal >=}, !=, {@literal <=}). The
* suggested idiom for performing these comparisons is:
* {@code (x.compareTo(y)} <<i>op</i>> {@code 0)}, where
* <<i>op</i>> is one of the six comparison operators.
*
* @param val {@code BigDecimal} to which this {@code BigDecimal} is
* to be compared.
* @return -1, 0, or 1 as this {@code BigDecimal} is numerically
* less than, equal to, or greater than {@code val}.
*/
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;
}
可以看到,分了2种情况,一种是含有小数位相同,另一种时不相同的情况。所以不管2个数的小数位是否相同,都会进行值的比较。
最后
以上就是无限咖啡为你收集整理的BigDecimal比较大小注意事项(equals)的全部内容,希望文章能够帮你解决BigDecimal比较大小注意事项(equals)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复