Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable double NaN comparison in C#

Tags:

c#

double

nan

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.

like image 579
Irish Yobbo Avatar asked Nov 28 '12 03:11

Irish Yobbo


People also ask

What is the value of double NaN?

NaN values are tested for equality by using the == operator, the result is false. So, no matter what value of type double is compared with double. NaN, the result is always false.

What is double NaN?

Double isNaN() method in Java with examples The isNaN() method of Java Double class is a built in method in Java returns true if this Double value or the specified double value is Not-a-Number (NaN), or false otherwise.

What is double NaN C#?

The Double. IsNaN() method in C# is used to return a value that indicates whether the specified value is not a number (NaN).


2 Answers

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.
}
like image 155
Jonathon Reinhart Avatar answered Oct 04 '22 11:10

Jonathon Reinhart


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

like image 39
Jeppe Stig Nielsen Avatar answered Oct 04 '22 12:10

Jeppe Stig Nielsen