Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare a float to NaN if comparisons to NaN always return false?

Tags:

c#

I have a float value set to NaN (seen in the Watch Window), but I can't figure out how to detect that in code:

if (fValue == float.NaN) // returns false even though fValue is NaN { } 
like image 472
Anthony Brien Avatar asked Mar 12 '09 14:03

Anthony Brien


People also ask

How does NaN compare to float?

NaN cannot be compared with any floating type value. This means that we'll get false for all comparison operations involving NaN (except “!= ” for which we get true). Hence, we cannot check for NaN by comparing with NaN using “==” or “!=

Can a float be NaN?

NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis.

Can you compare NaN?

Unlike all other possible values in JavaScript, it is not possible to use the equality operators (== and ===) to compare a value against NaN to determine whether the value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false . The isNaN() function provides a convenient equality check against NaN .

How NaN values behave while comparing with itself?

Why do comparisons of NaN values behave differently from all other values? That is, all comparisons with the operators ==, <=, >=, <, > where one or both values is NaN returns false, contrary to the behaviour of all other values.


1 Answers

You want float.IsNaN(...). Comparisons to NaN always return false, no matter what the value of the float is. It's one of the quirks of floating points.

That means you can do this:

if (f1 != f1) { // This conditional will be true if f1 is NaN. 

In fact, that's exactly how IsNaN() works.

like image 188
John Feminella Avatar answered Oct 09 '22 07:10

John Feminella