0E30 不为零

发布于 2024-12-25 08:08:26 字数 432 浏览 3 评论 0原文

我不知道如何处理new BigDecimal("0E30")。它的值为 0,但它不与 BigDecimal.ZERO 进行比较。请参阅下文:

System.out.println(new BigDecimal("0E30").add(BigDecimal.ONE));     // ---> 1
System.out.println(new BigDecimal("0E30").equals(BigDecimal.ZERO)); // ---> false

有人可以帮助我使比较正确吗(我知道我可以通过将 BigDecimal 转换为 double 来获得解决方法,但我想知道什么是正在进行)? 我正在使用 JRE 1.6.3。 谢谢

I dont know how to handle new BigDecimal("0E30"). Its value is 0 but it doesn't compare to BigDecimal.ZERO. See below:

System.out.println(new BigDecimal("0E30").add(BigDecimal.ONE));     // ---> 1
System.out.println(new BigDecimal("0E30").equals(BigDecimal.ZERO)); // ---> false

Could someone help me to make the comparison true (I know I can get a workaround by converting the BigDecimals to double, but I would like to know what is going on)?
I am using JRE 1.6.3.
thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

奢望 2025-01-01 08:08:26

来自 docs(重点是我的):

比较此 BigDecimal 与指定的 Object 是否相等。
与 CompareTo 不同,此方法仅在以下情况下才认为两个 BigDecimal 相等
它们在值和规模上相等(因此 2.0 不等于 2.00,当
以此方法进行比较)。

在本例中,比例不匹配。因此,您应该使用compareTo()。

BigDecimalequals()compareTo() 不一致的情况之一:

注意:如果使用 BigDecimals 作为键,应小心
在 SortedMap 或 SortedSet 中的元素中,作为 BigDecimal 的自然属性
排序与 equals 不一致。请参阅 Comparable、SortedMap 或
SortedSet 了解更多信息。

From the docs (emphasis is mine):

Compares this BigDecimal with the specified Object for equality.
Unlike compareTo, this method considers two BigDecimals equal only if
they are equal in value and scale (thus 2.0 is not equal to 2.00 when
compared by this method).

In this case, the scale doesn't match. So instead, you should use compareTo().

BigDecimal is one of the cases where equals() is inconsistent with compareTo():

Note: care should be exercised if BigDecimals are to be used as keys
in a SortedMap or elements in a SortedSet, as BigDecimal's natural
ordering is inconsistent with equals. See Comparable, SortedMap or
SortedSet for more information.

油焖大侠 2025-01-01 08:08:26

来自文档

public boolean equals(Object x)

    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。

From the docs:

public boolean equals(Object x)

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

Your scales are different. If you want them to compare equal, use compareTo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文