How to check if a value is Not a Number (NaN) in C#
Overview
The Double.IsNaN() method helps us to see if a certain value is a number or Not a Number (NaN). It returns a Boolean value. If the specified value is NaN, true is returned. Otherwise, it returns false.
Syntax
public static bool IsNaN (double d);
Syntax to check if a value is not a number in C#
Parameters
d: This is the double value that we are checking.
Return value
The Double.IsNaN() method returns a Boolean value, i.e., either true or false. It returns true if d is NaN. Otherwise, it returns false.
Note: Dividing a non-zero number by zero returns either
PositiveInfinityorNegativeInfinity, which are notNaN.
Code example
// use Systemusing System;// classclass DoubleIsNaN{// main methodstatic void Main(){// This will return "true".Console.WriteLine("IsNaN(0.0/0.0) == {0}.", Double.IsNaN(0.0/0.0) ? "true" : "false");// This will return "false"Console.WriteLine("IsNaN(78) == {0}.", Double.IsNaN(78.9898) ? "true" : "false");// This will return "false"Console.WriteLine("IsNaN(67000) == {0}.", Double.IsNaN(67000.00) ? "true" : "false");// This will return "false"Console.WriteLine("IsNaN(9.0/0) == {0}.", Double.IsNaN(9.0 /0) ? "true" : "false");}}
Explanation
- In lines 10, 13, 16, and 19, we check if the given values will give
NaNusing theDouble.IsNaN()method. We use the ternary operator (?:) to check if the method returnstrueorfalse. If it returnstrue, we printtrue. Otherwise, we printfalse.