2

How to check the float variable contain Real Numbers or not in C++ ?

ex: -1.#IND000 my value

How to determine whether it is Real numbers or like above numbers .

Pixel
  • 121
  • 2
  • 18
  • Possible duplicate of: [http://stackoverflow.com/questions/570669/checking-if-a-double-or-float-is-nan-in-c] (Checking if a double or float is nan in C++) – Stephen Quan May 09 '13 at 06:41
  • Stephen's link's good - though you have to dig a little: numbers can be +/- infinite as well as NaN: you can use e.g. isfinite() from boost: http://www.boost.org/doc/libs/1_38_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/fpclass.html – Tony Delroy May 09 '13 at 06:51

5 Answers5

2

converting into bool (explicitly o by mean of whatever logical operator) will give "false" for all values that are not "real" or that are 0, so

bool is_number(double d)
{ return d || d==0; } 

should be fine.

Emilio Garavaglia
  • 18,858
  • 2
  • 41
  • 60
2

There are functions like std::isnan in header <cmath>.

Angew is no longer proud of SO
  • 156,801
  • 13
  • 318
  • 412
1

These following returns true if it's a number, false otherwise:

bool test1(double d) { return d == d; }
bool test2(double d) { return d * 0.0 == 0.0; }

These's a good discussion on Checking if a double (or float) is nan in C++.

Community
  • 1
  • 1
Stephen Quan
  • 15,118
  • 3
  • 69
  • 63
1

A very simple way..

float a=3.9;
long b;
b=a;
if ((float)b==a)
    cout<<"Non-real, i.e. integer";
else
    cout<<"REAL";
Shishir Gupta
  • 1,356
  • 2
  • 14
  • 31
1

You can use '_isnan' in Visual Studio (it is included in float.h):

float T;

T=std::numeric_limits<double>::quiet_NaN(); //YOUR CALCS HERE!!

if (_isnan(T)) {
    printf("error\n");
}
ALM865
  • 970
  • 11
  • 19