Checking if a double (or float) is NaN in C++



In this article we will check whether a double or floating point number is NaN (Not a Number) in C++.

Checking if a Double or Floating Point Number is NaN

To check, we can utilise the isnan() method. The isnan() function is available in the cmath library. This function was introduced in C++ version 11. So From C++11 next, we can use this function.

The isnan() function is used to determine whether a double or floating point number is not-a-number (NaN) value. Return true if num is NaN, false otherwise.

C++ Program to Check Double or Float Number is NaN

In the following example, we are checking a floating point and double number is NaN using the isnan() function in C++:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
   // Produces NaN
   float floatValue = sqrt(-1.0f);
   // Also produces NaN
   double doubleValue = 0.0 / 0.0;

   // Check float
   if (isnan(floatValue)) {
      cout << "floatValue is NaN." << endl;
   } else {
      cout << "floatValue is valid." << endl;
   }

   // Check double
   if (isnan(doubleValue)) {
      cout << "doubleValue is NaN." << endl;
   } else {
      cout << "doubleValue is valid." << endl;
   }
   return 0;
}

Following is the output:

floatValue is NaN.
doubleValue is NaN.
Updated on: 2025-06-18T18:47:53+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements