user1899020
user1899020

Reputation: 13575

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

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

float f;
???

Upvotes: 10

Views: 2164

Answers (4)

Bathsheba
Bathsheba

Reputation: 234715

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

Upvotes: 1

eerorika
eerorika

Reputation: 238351

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.

Upvotes: 11

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122468

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.

Upvotes: 5

DevSolar
DevSolar

Reputation: 70263

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.

Upvotes: 2

Related Questions