Equality with Double.NaN
Asked Answered
G

5

39

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.

Gannie answered 17/2, 2009 at 19:1 Comment(0)
O
65

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));
}
Overprize answered 17/2, 2009 at 19:5 Comment(1)
Does ‘is NaN’ test correctly for C#7 pattern matching? if (xxx is Double.NaN).Juni
C
39

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.

Craps answered 17/2, 2009 at 19:5 Comment(1)
See comment to original question. -- I'm stuck with an existing database from years back.Gannie
G
10

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.

Gaylenegayler answered 17/2, 2009 at 19:6 Comment(1)
Unless you use .Equals!Faqir
E
8

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

Eustache answered 24/5, 2010 at 14:47 Comment(3)
No. See Reference sourceCommensal
I tested this: IsNaN() DOES work, while comparison does not.Jay
@Jay Test again, or prove it.Eustache
J
0

If you are lazy, like me, you can use the following extension method:

[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool IsNaN( this System.Single v ) {
    return System.Single.IsNaN( v );
}

You would need another one for System.Double.

Jay answered 29/11, 2023 at 5:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.