Nullable double NaN comparison in C#

2020-03-24 03:28发布

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.

标签: c# double nan
3条回答
对你真心纯属浪费
2楼-- · 2020-03-24 03:40

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#).

查看更多
We Are One
3楼-- · 2020-03-24 03:47

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

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-03-24 03:51

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.
}
查看更多
登录 后发表回答