Can float (or double) be set to NaN?
Asked Answered
G

4

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?

Gemmell answered 14/9, 2011 at 15:50 Comment(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.Autoerotism
B
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

Breton answered 14/9, 2011 at 15:53 Comment(3)
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.Gemmell
No, the constant is for the primitive type.Breton
Ok, sorry, you edited before I finished this comment, thanks for the clarification.Gemmell
E
12

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

double x = Double.NaN;
Evenson answered 14/9, 2011 at 15:54 Comment(0)
D
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.

Dovecote answered 14/9, 2011 at 15:53 Comment(0)
S
0

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

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

Suffrage answered 2/9, 2022 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.