BigDecimal等值比较:精度影响相等性判断

小豆丁 25天前 ⋅ 25 阅读
聊天记录
头像

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. Therefore 2.0 is not equal to 2.00 when compared by this method since the former has [BigInteger, scale] components equal to [20, 1] while the latter has components equal to [200, 2]. Params: x – Object to which this BigDecimal is to be compared. Returns: true if and only if the specified Object is a BigDecimal whose value and scale are equal to this BigDecimal's. API Note: One example that shows how 2.0 and 2.00 are not substitutable for each other under some arithmetic operations are the two expressions: new BigDecimal("2.0" ).divide(BigDecimal.valueOf(3), HALF_UP) which evaluates to 0.7 and new BigDecimal("2.00").divide(BigDecimal.valueOf(3), HALF_UP) which evaluates to 0.67. The behavior of this method is analogous to checking the representation equivalence of double values. See Also: compareTo(BigDecimal), hashCode 是什么啥意思?

头像

这段是Java官方文档对BigDecimal.equals()方法的详细解释。我来逐句翻译和解释:

逐句解析

"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."

  • 比较这个BigDecimal与指定对象是否相等。与compareTo不同,此方法仅当两个BigDecimal对象在**值和精度(scale)**上都相等时才认为它们相等。

"Therefore 2.0 is not equal to 2.00 when compared by this method since the former has [BigInteger, scale] components equal to [20, 1] while the latter has components equal to [200, 2]."

  • 因此,用此方法比较时,2.0不等于2.00,因为前者的组件是[20, 1](未缩放值=20,精度=1),而后者的组件是[200, 2](未缩放值=200,精度=2)。

"Params: x – Object to which this BigDecimal is to be compared."

  • 参数:x - 要与此BigDecimal比较的对象。

"Returns: true if and only if the specified Object is a BigDecimal whose value and scale are equal to this BigDecimal's."

  • 返回:当且仅当指定对象是一个BigDecimal,且其值和精度都与此BigDecimal相等时返回true。

关键示例解释

文档中的除法例子说明了为什么精度很重要:

JAVA
new BigDecimal("2.0").divide(BigDecimal.valueOf(3), HALF_UP)   // 结果: 0.7 (精度1)
new BigDecimal("2.00").divide(BigDecimal.valueOf(3), HALF_UP)  // 结果: 0.67 (精度2)

这说明:

  • 2.0 ÷ 3 = 0.7(保留1位小数)
  • 2.00 ÷ 3 = 0.67(保留2位小数)
  • 相同的数学运算,因初始精度不同,得到不同结果

核心要点

  1. 精度影响计算行为:精度不仅影响显示,还影响算术运算的结果
  2. 设计意图equals()严格比较是为了确保两个BigDecimal在所有计算场景下可互换
  3. 与double类比:就像比较两个double的二进制表示是否完全相同

实际应用建议

JAVA
// 业务比较:通常用compareTo()
if (price1.compareTo(price2) == 0) {
    // 数值相等即可
}

// 严格比较:需要完全一致时才用equals()
if (exactValue1.equals(exactValue2)) {
    // 值和精度都必须完全匹配
}

这就是为什么你的53.053.00equals()比较返回false的原因。

全部评论: 0

    我有话说: