简体   繁体   中英

Is comparing double values using == deterministic

import java.math.BigDecimal;

public class HelloWorld{

     public static void main(String []args){
        BigDecimal previousOperationAmount = new BigDecimal(1149.35);
        Double requestedAmount = 1149.35;

        if (requestedAmount != previousOperationAmount.doubleValue()) {
            System.out.println("Hello 1");
        }

        if(!requestedAmount.equals(previousOperationAmount.doubleValue())) {
            System.out.println("Hello 2");
        }
     }
}

There are two ways to compare double values.. One is with != operator and one is with .equals operator. I understand that .equals is better way to compare. But here, != comparison is also not giving any error .

Is is ok to use != comparison for double values ? Is != check for double values deterministic ?

The difference is clearly specified in the documentation :

Note that in most cases, for two instances of class Double , d1 and d2 , the value of d1.equals(d2) is true if and only if

 d1.doubleValue() == d2.doubleValue() 

also has the value true . However, there are two exceptions:

  • If d1 and d2 both represent Double.NaN , then the equals method returns true , even though Double.NaN==Double.NaN has the value false .
  • If d1 represents +0.0 while d2 represents -0.0 , or vice versa, the equal test has the value false , even though +0.0==-0.0 has the value true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM