Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
nan
communitycreator

How to check if a value is Not a Number (NaN) in C#

Theodore Kelechukwu Onyejiaku

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 PositiveInfinity or NegativeInfinity, which are not NaN.

Code example

// use System
using System;
// class
class DoubleIsNaN
{
    // main method
    static 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");

    }
}
Checking if a value is NaN in C#

Explanation

  • In lines 10, 13, 16, and 19, we check if the given values will give NaN using the Double.IsNaN() method. We use the ternary operator (?:) to check if the method returns true or false. If it returns true, we print true. Otherwise, we print false.

RELATED TAGS

c#
nan
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring