Is there a way to check if a variable is an integer? C ++

I need to check if a variable is an integer, for example, I have code:

double foobar = 3; //Pseudocode if (foobar == whole) cout << "It whole"; else cout << "Not whole"; 

How can I do it?

+6
source share
4 answers

Assuming foobar is a floating point value, you can round it and compare with the number itself:

 if (floor(foobar) == foobar) cout << "It whole"; else cout << "Not whole"; 
+13
source

You use int, so it will always be an integer. But if you use double, you can do something like this

 double foobar = something; if(foobar == static_cast<int>(foobar)) return true; else return false; 
+2
source

Depends on your definition of an integer. If you consider only 0 and above an integer, then this is simple: bool whole = foobar >= 0; .

+1
source

just write function or expression to check the whole number , returning bool .

in the usual definition, I think the integer is greater than 0 without the decimal part.

then

 if (abs(floor(foobar) )== foobar) cout << "It whole"; else cout << "Not whole"; 
0
source

Source: https://habr.com/ru/post/910224/


All Articles