文章目录
- BigDecimal 0 不等于 0.00 equals问题
- 问题场景
- 解决办法
- 复现和修复的代码
BigDecimal 0 不等于 0.00 equals问题
问题场景
在执行某退款时,需要检验一下公式是否相等,避免在数据异常时执行了退款,但出现了一个问题,左边为0,右边计算后为0.00,使用BigDecimal 的equals方法去判定BigDecimal的0 和BigDecimal的0.00返回不相等!
天猫前置抵扣退款结算时:质检价0 != 前置抵扣已使用金额0+本次结算前线下结算额-9200.00+本次退款金额9200.00
BigDecimal 的equals方法源码如下,在精度不一致的时候会提前返回不相等~
/**
* Compares this {@code BigDecimal} with the specified
* {@code Object} for equality. Unlike {@link
* #compareTo(BigDecimal) compareTo}, this method considers two
* {@code 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).
*
* @param x {@code Object} to which this {@code BigDecimal} is
* to be compared.
* @return {@code true} if and only if the specified {@code Object} is a
* {@code BigDecimal} whose value and scale are equal to this
* {@code BigDecimal}'s.
* @see #compareTo(java.math.BigDecimal)
* @see #hashCode
*/
@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());
}
解决办法
请使用compareTo == 0来判断
复现和修复的代码