Sunday, December 29, 2013

JavaScript, C# and NaN

You may already know that in JavaScript NaN is not equal to NaN.

Number("1")
1

Number("aa")
NaN

// What? Yes!
Number("aa") === Number("aa")
false

// To compare a possible NaN value we must use the function isNaN()
isNaN(Number("aa"))
true

What I did not know and you may not is that

It is the same in C#!

I was not expecting it.
First let us look at a C# sample.

static double zero;

static void Main()
{
    var d = 0/zero;
    Console.WriteLine(d == double.NaN);             // <= False
    Console.WriteLine(double.IsNaN(d));             // <= True
    Console.WriteLine(double.NaN == double.NaN);    // <= False
    Console.WriteLine(Math.Sqrt(-4));               // <= NaN
}
In the end it is part of the IEEE-754 floating point standard.
If you want to know more about NaN, see What Every Computer Scientist Should Know About Floating-Point Arithmetic, and search for "Special Quantities".

An other good reference: C# in Depth - Binary floating point and .NET

No comments:

Post a Comment