Is there a way to check if a variable is a whole number? C++
The answer of laurent is great, here is another way you can use without the function floor
#include <cmath> // fmod
bool isWholeNumber(double num)
{
reture std::fmod(num, 1) == 0;
// if is not a whole number fmod will return something between 0 to 1 (excluded)
}
fmod function
Assuming foobar
is in fact a floating point value, you could round it and compare that to the number itself:
if (floor(foobar) == foobar)
cout << "It's whole";
else
cout << "Not whole";
You are using int so it will always be a "whole" number. But in case you are using a double then you can do something like this
double foobar = something;
if(foobar == static_cast<int>(foobar))
return true;
else
return false;