Testing for NaN

I was in the middle of building a Windows Phone 8 application when I ran into an interesting problem. My application tracks where the phone is and uses it as the center point on the map that is being displayed. I wanted the map to be adjust its heading to match the direction that the phone (user) is heading. It seemed simple enough. The Geolocator PositionChanged event passes into the handler “PositionChangedEventArgs”. The args then has a property of Position.Coordinate.Heading that is of type double?. The ? part of the type indicates that it is nullable. When it is null it comes back as NaN (not a number). No, problem (I thought). I’ll just do a check like this:

if(args.Position.Coordinate.Heading != null) …

But it always returned True. So I tried:

if(args.Position.Coordinate.Heading != Double.NaN) …

But it always returned True. Well, for reasons I won’t get into here, even if you do the following check it will always return false: Double.NaN == Double.NaN

But, I found a sneaky way (reading specifications is so helpful!) around the problem. It turns out there is a CompareTo method on the Double.NaN. If the value you are comparing is indeed a NaN, then the return value will be 0. If it returns 1 or -1, then the result is indeed a number. So, I changed my implementation to include the following:

double? tmp = args.Position.Coordinate.Heading;

            if (Double.NaN.CompareTo(tmp) != 0) …

And that seemed to do the trick. Hope this is helpful to you!


About lelandholmquest

After serving in the Navy as a Reactor Operator on fast attack submarines, I earned both a Bachelor's and Masters in Information Technology from American InterContinental University and am currently working on my doctorate. I have a beautiful wife and two of the sweetest daughters a man could ask for. And I work for the greatest company: Microsoft. At Microsoft I work on the knowledge management system for Microsoft Services: Campus on Office 365.
This entry was posted in C# Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s