Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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

float f;
???
like image 277
user1899020 Avatar asked Jun 09 '16 15:06

user1899020


2 Answers

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.

like image 141
eerorika Avatar answered Sep 27 '22 21:09

eerorika


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.

like image 37
463035818_is_not_a_number Avatar answered Sep 27 '22 22:09

463035818_is_not_a_number