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;
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