Nullable double NaN comparison in C#
c#, double, nan
Solution
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.
}
Problem
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.