问题描述
实际上,我已经找到了可能的解决方案
Actually, I've found possible solution
//returns true
new BigDecimal("5.50").doubleValue() == new BigDecimal("5.5").doubleValue()
当然,可以通过类似Math.abs (v1 - v2) < EPS
的方法进行改进,以使比较更可靠,但问题是该技术是否可以接受?或者是否有更好的解决方案?
Of course, it can be improved with something like Math.abs (v1 - v2) < EPS
to make the comparison more robust, but the question is whether this technique acceptable or is there a better solution?
如果有人知道为什么Java设计人员决定以这种方式实现BigDecimal的equals,那么阅读它会很有趣.
If someone knows why java designers decided to implement BigDecimal's equals in that way, it would be interesting to read.
推荐答案
来自BigDecimal的javadoc
From the javadoc of BigDecimal
public boolean equals(Object x)
将此BigDecimal
与指定的Object
进行相等性比较.与 compareTo
,则此方法仅在两个BigDecimal
对象的值和比例相等时才认为它们相等.因此,此方法比较时,2.0不等于2.00 .
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 (thus 2.0 is not equal to 2.00 when compared by this method).
只需使用compareTo() == 0
这篇关于为什么BigDecimal("5.50")不等于BigDecimal("5.5"),以及如何解决此问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!