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
andd2
, the value ofd1.equals(d2)
istrue
if and only ifd1.doubleValue() == d2.doubleValue()
also has the value
true
. However, there are two exceptions:
- If
d1
andd2
both representDouble.NaN
, then theequals
method returnstrue
, even thoughDouble.NaN==Double.NaN
has the valuefalse
.- If
d1
represents+0.0
whiled2
represents-0.0
, or vice versa, the equal test has the valuefalse
, even though+0.0==-0.0
has the valuetrue
.
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.