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 { }
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 “!=
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With