24

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?

Community
  • 1
  • 1
ahodder
  • 11,353
  • 14
  • 71
  • 114
  • 1
    I wouldn't say there's little practical purpose. For instance I am using this method to specify failed results in a table of doubles. – Robin Newhouse Jun 14 '14 at 00:28

4 Answers4

28

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

Codemwnci
  • 54,176
  • 10
  • 96
  • 129
  • I thought that was just a constant representation for a wrapper class (but the constant is still a valid number)? I'm looking for setting the `float` or `double` to NaN, thus making it unusable in any arithmatic. – ahodder Sep 14 '11 at 15:55
  • No, the constant is for the primitive type. – Codemwnci Sep 14 '11 at 15:56
  • Ok, sorry, you edited before I finished this comment, thanks for the clarification. – ahodder Sep 14 '11 at 15:56
12

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

double x = Double.NaN;
japreiss
  • 11,111
  • 2
  • 40
  • 77
9

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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

jshell> double ddd=Double.NaN; ddd ==> NaN

jshell> ddd!=ddd $5 ==> true

27P
  • 1,183
  • 16
  • 22