How to check if float is a true number in C ++?

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

float f; ??? 
+7
c ++
source share
4 answers

Easier than std::fpclassify() use std::isfinite()

Determines whether a given floating point number has a finite value, that is, it is normal, subnormal, or zero, but not infinite or NaN.

+7
source share

std :: isnormal () does what you want, but also checks for 0.0. So you can check this case further:

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

Edit: as specified by user isnormal also returns false for the subnormal number that the OP probably does not want.

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

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

it returns false for NaN and Inf .

+5
source share

For C ++ 11 onwards, use !std::isnan(f) && !std::isinf(f) to verify that the number is neither NaN nor infinity (positive or negative).

Pre-C ++ 11 is a little more complicated, but you can do it anyway. If your platform uses IEEE754 for float , you can use:

  • f == f will be false only for the case of NaN.

  • Something from 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

+1
source share

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 an implementation type defining the category arg .

+1
source share

All Articles