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). Howev
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#).
With C# 7.0 Pattern matching combined null + NaN check check can be written like this:
double? d = whatever;
if(d is double val && double.IsNaN(val))
Console.WriteLine(val);
The advantage is local scoped variable val
at hand, which is not null
, nor double.NaN
and can even be used outside of if
.
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.
}
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