在Java中使用等于零的运算符(BigDecimal / Double) [英] Equals operator for zeros (BigDecimal / Double) in Java

查看:330
本文介绍了在Java中使用等于零的运算符(BigDecimal / Double)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些有趣的观察wrt在0和0.0之间等于运算符

A few interesting observations w.r.t equals operator on 0 and 0.0


  1. new Double(0.0) 返回false,而 new Double(0.0).equals(0.0)返回true

  1. new Double(0.0).equals(0) returns false, while new Double(0.0).equals(0.0) returns true.

BigDecimal.ZERO.equals(BigDecimal.valueOf(0.0))返回false,而 BigDecimal.ZERO。等于(BigDecimal.valueOf(0))返回true

BigDecimal.ZERO.equals(BigDecimal.valueOf(0.0)) returns false, while BigDecimal.ZERO.equals(BigDecimal.valueOf(0)) returns true.

看起来像字符串在这两种情况下都进行了比较。

Looks like the string comparison is being done in both the cases. Could anyone throw some light on this.

谢谢。

推荐答案

BigDecimal'equals'比较值和比例。如果你只想比较值(0 == 0.0),你应该使用compareTo:

BigDecimal 'equals' compares the value and the scale. If you only want to compare values (0 == 0.0) you should use compareTo:

BigDecimal.ZERO.compareTo(BigDecimal.valueOf(0.0)) == 0 //true
BigDecimal.ZERO.compareTo(BigDecimal.valueOf(0)) == 0 //true

请参阅 javadoc

对于双重比较,如其他答案所解释的,您正在比较双在新的Double(0.0).equals(0)中返回 false 的整数,因为对象具有不同的类型。作为参考, JDK 7中的equals方法的代码是:

As for the Double comparison, as explained by other answers, you are comparing a Double with an Integer in new Double(0.0).equals(0), which returns false because the objects have different types. For reference, the code for the equals method in JDK 7 is:

public boolean equals(Object obj) {
    return (obj instanceof Double)
           && (doubleToLongBits(((Double)obj).value) ==
                  doubleToLongBits(value));
}

在您的情况下,(obj instanceof Double)是false。

In your case, (obj instanceof Double) is false.

这篇关于在Java中使用等于零的运算符(BigDecimal / Double)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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