tags:

views:

1034

answers:

4

I have the following code...

if (Price_Foreign != Double.NaN)
{
   output.Append(spacer);
   output.Append(String.Format("{0,-10:C} USD",Price_Foreign));
}

Which outputs:

NaN USD

What gives?

I'm using Double.NaN to indicate that the value doesn't exist, and shouldn't be output.

+8  A: 

Perhaps you are looking for the IsNaN static function?

Try something like this:

if (!Double.IsNaN(Price_Foreign))
{
   output.Append(spacer);
   output.Append(String.Format("{0,-10:C} USD",Price_Foreign));
}
Andrew Hare
Yup, that did it.
chris
+9  A: 

The IEEE 754 floating point standard states that comparing NaN with NaN will always return false. If you must do this, use Double.isNaN().

But, this isn't the best way to do what you're trying to do. Doubles are NOT precise, and you're using them to represent prices here. I'm betting that at some point, you're going to want to compare prices for equality, too. That's not going to work, because you can't rely on floating point equality.

You should really look into using some integer type for these values (that supports equality comparison) rather than trying to use doubles. Doubles are for scientific problems; not for finance.

tgamblin
See comment to original question. -- I'm stuck with an existing database from years back.
chris
+3  A: 

Double.NaN is not equal to anything, not even itself.

See the Double.NaN Field in the .NET Framework Class Library documentation:

Use IsNaN to determine whether a value is not a number. It is not possible to determine whether a value is not a number by comparing it to another value equal to NaN.

Grant Wagner
+1  A: 

As background information: what the IsNaN() method does is return v != v;

Martijn Courteaux