Nullable double NaN comparison in C#

2020-03-24 03:45发布

问题:

I have 2 nullable doubles, an expected value and an actual value (let's call them value and valueExpected). A percentage is found using 100 * (value / valueExpected). However, if valueExpected is zero, it returns NaN. Everything good so far.

Now, what do I do if I need to check the value, to see if it is NaN? Normally one could use:

if (!Double.IsNaN(myDouble))

But this doesn't work with nullable values (IsNaN only works with non-nullable variables). I have changed my code to do the check (valueExpected == 0), but I'm still curious - is there any way to check for a nullable NaN?

Edit: When I say the code doesn't work, I mean it won't compile. Testing for null first doesn't work.

回答1:

With all Nullable<T> instances, you first check the bool HasValue property, and then you can access the T Value property.

double? d = 0.0;        // Shorthand for Nullable<double>
if (d.HasValue && !Double.IsNaN(d.Value)) {
    double val = d.Value;

    // val is a non-null, non-NaN double.
}


回答2:

You can also use

if (!Double.IsNaN(myDouble ?? 0.0))

The value in the inner-most parenthesis is either the myDouble (with its Nullable<> wrapping removed) if that is non-null, or just 0.0 if myDouble is null. Se ?? Operator (C#).



回答3:

I had the same issue and I solved it with casting the double? with double

double.IsNaN((double)myDouble)

this will return true if NaN and false if not



标签: c# double nan