Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

C#: Never Test For NaN With Equality Test

0.00/5 (No votes)
15 Jan 2020 4  
Never compare NaN with itself!

Let's write a simple program to test. To get a NaN, we do a 0/0 and store it in num. First of all, the divisor has to be a float-point type because DivideByZeroException shall be thrown for integer or decimal zero divisor. Note: Non-zero number divided by zero (float) gives an infinity number. In our program, we compare num to NaN and next, compare num to itself and then, we compare 2.0 to NaN. Lastly, we check if num is NaN with Double.IsNaN().

double num = 0.0 / 0.0; // Result of 0 divided by 0 is a NaN

Console.WriteLine("num == NaN is {0}", (num == double.NaN));
Console.WriteLine("num == num is {0}", (num == num));
Console.WriteLine("2.0 == NaN is {0}", (2.0 == double.NaN));
Console.WriteLine("double.IsNaN(num) is {0}", double.IsNaN(num));

This is the output. All the 3 NaN comparisons return False while IsNaN() check on num returns True. This is exactly the same behaviour with C++. The advice for this tip is never test for NaN with equality test, use IsNaN() instead.

num == NaN is False
num == num is False
2.0 == NaN is False
double.IsNaN(num) is True

If you are interested to know more about floating-point format, read my Succinct Guide to Floating Point Format For C++ and C# Programmers.

History

  • 16th January, 2020: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here