Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top