Java - Compare floating-point types for equality

Negative Zero vs positive zero

Both negative zero (-0.0) and positive zero (0.0) are considered equal.

double d1 = 0.0; 
double d2 = -0.0; 
boolean b = (d1 == d2); // Assigns true to b 

Demo

public class Main {
  public static void main(String[] args) {
    double d1 = 0.0; 
    double d2 = -0.0; 
    boolean b = (d1 == d2); // Assigns true to b 
    System.out.println(b); /*w ww  .  j  ava2  s  .  com*/
  }
}

Result

Infinity

A positive infinity is equal to another positive infinity.

A negative infinity is equal to another negative infinity.

A positive infinity is not equal to a negative infinity.

double d1 = Double.POSITIVE_INFINITY; 
double d2 = Double.NEGATIVE_INFINITY; 
boolean b1 = (d1 == d2); // Assigns false to b1 
boolean b2 = (d1 == d1); // Assigns true to b2 

Demo

public class Main {
  public static void main(String[] args) {
    double d1 = Double.POSITIVE_INFINITY; 
    double d2 = Double.NEGATIVE_INFINITY; 
    boolean b1 = (d1 == d2); // Assigns false to b1 
    boolean b2 = (d1 == d1); // Assigns true to b2 
    System.out.println(b1);/*ww w .java2  s .  co m*/
    System.out.println(b2);
  }
}

Result

NaN

If either operand is NaN, the equality test returns false.

double d1 = Double.NaN; 
double d2 = 5.5; 
boolean b = (d1 == d2); // Assigns false to b 

Demo

public class Main {
  public static void main(String[] args) {
    double d1 = Double.NaN; 
    double d2 = 5.5; 
    boolean b = (d1 == d2); // Assigns false to b 

    System.out.println(b);//from   ww  w .j a  v  a2 s .  c  o  m
  }
}

Result

Even if both the operands are NaN, the equality operator will return false.

d1 = Double.NaN; 
d2 = Double.NaN; 
b = (d1 == d2); // Assigns false to b 

Demo

public class Main {
  public static void main(String[] args) {
    double d1 = Double.NaN; 
    double d2 = Double.NaN; 
    boolean b = (d1 == d2); // Assigns false to b 

    System.out.println(b);/*from  w  ww  .j  av  a2  s. c  om*/
  }
}

Result

Float and Double classes have an isNaN() method, which accepts a float and a double argument, respectively.

It returns true if the argument is NaN, Otherwise, it returns false.

double d1 = Double.NaN; 
b = Double.isNaN(d1); 

Demo

public class Main {
  public static void main(String[] args) {
    double d1 = Double.NaN; 
    //from  w ww  . j  a va 2 s.  co m
    boolean b = Double.isNaN(d1); 

    System.out.println(b);
  }
}

Result

Related Topic