10

How to check if a float number is a true number? That is: it is not infinity, negative infinity, NaN ...

float f;
???
user1899020
  • 12,499
  • 17
  • 70
  • 145
  • 2
    You mean functions like [`std::isnan`](http://en.cppreference.com/w/cpp/numeric/math/isnan)? That's C++11 but does the job. – tadman Jun 09 '16 at 15:33
  • 2
    Have you seen [std::isfinite](http://en.cppreference.com/w/cpp/numeric/math/isfinite) and the related functions? – James Adkison Jun 09 '16 at 15:34
  • you mean a *real* number? Because a number is true if it's different from 0.0 – phuclv Jun 09 '16 at 15:45
  • 1
    Please [edit](http://stackoverflow.com/posts/37730313/edit) your question to not use `...` and instead fully explain what aspects must be considered to meet your definition of _true_. – James Adkison Jun 09 '16 at 15:46

4 Answers4

10

Simpler than std::fpclassify() is to use std::isfinite()

Determines if the given floating point number arg has finite value i.e. it is normal, subnormal or zero, but not infinite or NaN.

eerorika
  • 223,800
  • 12
  • 181
  • 301
5

std::isnormal() does what you want but it also checks for 0.0. So you might check that case extra:

float f;
bool isNumber = (std::isnormal(f) || f == 0.0);

Edit: as pointed out by user2079303 isnormal also returns false for a subnormal number which the OP probably does not want.

However, maybe std::isfinite does the right thing.

float f;
bool isNumber = std::isfinite(f) ;

it returns false for NaN and Inf.

Community
  • 1
  • 1
463035818_is_not_a_number
  • 88,680
  • 9
  • 76
  • 150
1

For C++11 and onwards, use !std::isnan(f) && !std::isinf(f) to test for a number being neither NaN nor infinity (positive or negative).

Pre-C++11 it's a bit more difficult, but you can still do it. If your platform uses IEEE754 for the float then you can use:

  1. f == f will be false only for the NaN case.

  2. Something of the form f == f / 2 will be true only for infinity or a number close to zero, and you can trivially eliminate the latter case.

Boost (www.boost.org) also provides methods for pre C++11. See http://www.boost.org/doc/libs/1_41_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/fpclass.html

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
1

std::fpclassify() looks like what you are looking for.

int fpclassify( float arg );
int fpclassify( double arg );
int fpclassify( long double arg );
int fpclassify( Integral arg );

Return value

one of FP_INFINITE, FP_NAN, FP_NORMAL, FP_SUBNORMAL, FP_ZERO or implementation-defined type, specifying the category of arg.

DevSolar
  • 63,860
  • 19
  • 125
  • 201