为什么BigDecimal("5.50")不等于BigDecimal("5.5"),以及如何解决此问题? [英] Why BigDecimal("5.50") not equals to BigDecimal("5.5") and how to work around this issue?

查看:606
本文介绍了为什么BigDecimal("5.50")不等于BigDecimal("5.5"),以及如何解决此问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我已经找到了可能的解决方案

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"),以及如何解决此问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆