Float.NaN == Float.NaN

shrini1000 picture shrini1000 · Feb 18, 2012 · Viewed 25.9k times · Source

Why does this comparison give me 'false'? I looked at the source and Float.NaN is defined as

/** 
 * A constant holding a Not-a-Number (NaN) value of type
 * <code>float</code>.  It is equivalent to the value returned by
 * <code>Float.intBitsToFloat(0x7fc00000)</code>.
 */
public static final float NaN = 0.0f / 0.0f;

EDIT: surprisingly, if I do this:

System.out.println("FC " + (Float.compare(Float.NaN, Float.NaN)));

it gives me 0. So Float.compare() does think that NaN is equal to itself!

Answer

pencil picture pencil · Feb 18, 2012

Use Float.isNaN to check for NaN values.