What the hell is NaN?

Someone who was doing a code review for me asked me this question, and how it related to .NET development in general. Funny misconception about NaN, it is not just limited to .NET compatible languages, but is actually an enter computer science concept, to represent an invalid file output based on invalid input operands. I have never used it for anything besides floating point calculations.

The code in question was a condition statement that was taking a SPListItem as a parameter, and was used to check whether the item was a double precision floating number. For this NaN was a definitely a good option! Here is the code:


double isDouble(SPListItem ListItem)
if (this._yourField == SPFieldType.Number)
string iListName = ListItem[this._somestring].ToString();
return double.Parse(iListName);
return double.NaN;
return double.NaN;


I suppose that there are other ways that you could use a custom method to do the same type of test, but this is small and efficient.


4 thoughts on “What the hell is NaN?”

  1. Why not simply use Double.TryParse(iListName,out doubleValue)?

    That would make you get rid of that nasty catch all. At least i would use a specific catch -FormatException and ArgumentNullException as to not hide other exceptions :-)

  2. Yeah, TryParse is MUCH better. Creating an exception is a much more expensive operation that just testing the parse first. If you’ve got a situations where you’re doing a lot of Parse operations, and they’re failing, your app will big significantly slower.

    Unless, of course, you want the exception raised – but that’s not the case here…

  3. That is a good point, I really didn’t have to think about the exception tax in this particular piece, but that is good advice for people to consider.

    I wanted to verify it, so I modified this app:


    to benchmark the two pieces with both pieces of code. The results (minus the bloat that is introduced with NaN) was:

    NaN Test = 11 msec
    TryParse = 2 msec

    (Taking into account this would depend on compiler settings and OS).

    Quite a difference indeed!

    Andy’s point should also be well-observed too I believe. If you do have several parse operations, it could become a real performance hog!

  4. Also by using TryParse you get a boolean back (you could get the double using out in args too) which I would consider a cleaner approach -the method is called IsDouble after all.

Leave a Reply

Your email address will not be published. Required fields are marked *