Equals operator for zeros (BigDecimal / Double) in Java

后端 未结 7 1156
别那么骄傲
别那么骄傲 2020-12-14 06:31

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

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

7条回答
  •  离开以前
    2020-12-14 06:40

    1. The 0 in your first expression is interpreted as an int, which may be autoboxed into an Integer, but not to a Double. So the type of the two is different, hence they are not equal. OTOH 0.0 is a double, which is autoboxed into a Double, so the two operands are deemed equal.

    2. BigDecimals also contain a scale (i.e. number of digits to the right of the decimal separator dot). BigDecimal.ZERO has the value of "0", so its scale is 0. Hence it is not equal to "0.0", whose scale is 1.
      If you want to compare values, use BigDecimal.compareTo:

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

提交回复
热议问题