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.
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.
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.
The Double. IsNaN() method in C# is used to return a value that indicates whether the specified value is not a number (NaN).
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.
}
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#).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With