When calling Double.IsNaN()
with Double.PositiveInfinity
as argument, the result is false. This is against my intuition since infinity is not a number. Apparently "NaN" only exists in terms of a constant in .NET, is this described by the IEEE standard or is it a custom implementation detail? Is there a shorter way to check if a Double
is "NaN" than:
(Double.IsNaN(d) || Double.IsPositiveInfinity(d) || Double.IsNegativeInfinity(d))
or
(Double.IsNaN(d) || Double.IsInfinity(d))
isNaN() Method: To determine whether a number is NaN, we can use the isNaN() function. It is a boolean function that returns true if a number is NaN otherwise returns false.
To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.
IsNaN() is a Double struct method. This method is used to check whether the specified value is not a number (NaN). Return Type: This function returns a Boolean value i.e. True, if specified value is not a number(NaN), otherwise returns False. Code: To demonstrate the Double.
As MSDN says, NaN means that result is undefined. With infinities result is defined:
A method or operator returns NaN when the result of an operation is undefined. For example, the result of dividing zero by zero is NaN, as the following example shows. (But note that dividing a non-zero number by zero returns either PositiveInfinity or NegativeInfinity, depending on the sign of the divisor.)
So, it's not good idea to tread infinities as NaN. You can write extension method to check if value is not NaN or infinity:
// Or IsNanOrInfinity public static bool HasValue(this double value) { return !Double.IsNaN(value) && !Double.IsInfinity(value); }
You no longer need an extension from SergeyBerezovskiy answer.
double
has IsFinite()
method to check if a double is a finite number (is not NaN
or Infinity
):
double.IsFinite(d)
See source code in .Net Framework and .Net Core
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