Can float (or double) be set to NaN?

22,698

Solution 1

The Float object contains a static value, which is a float type, called NaN.

So

float myFloat = Float.NaN;

gives you what you are asking.

http://download.oracle.com/javase/6/docs/api/java/lang/Float.html#NaN

Solution 2

Sure! NaN is a static constant in the Float and Double classes.

double x = Double.NaN;

Solution 3

Yes

float f = Float.NaN;

See the doc for more info. Note that if you want to compare a number to NaN, you should use isNan().

Despite your question above, this does have a practical purpose. You can use this to indicate a value hasn't been set/provided yet.

Share:
22,698
ahodder
Author by

ahodder

I'm a derp who derps with herps in hopes that the herp does all the derping I want it to.

Updated on May 12, 2020

Comments

  • ahodder
    ahodder almost 4 years

    Note: Similar to Can an integer be NaN in C++?

    I understand this has little practical purpose, but can a float or double be set to NaN?