I need to check if a variable is a whole number, say I have the code:
double foobar = 3;
//Pseudocode
if (foobar == whole)
cout << \"It\'s 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;
just write a function
or expression
to Check for whole number
, returning bool
.
in usual definition i think whole number is greater than 0 with no decimal part.
then,
if (abs(floor(foobar) )== foobar)
cout << "It's whole";
else
cout << "Not whole";
Depends on your definition of whole number. If you consider only 0 and above as whole number then it's as simple as: bool whole = foobar >= 0;
.
All you have to do is define your possible decimal number as an int and it will automatically round it, then compare the double with the int. For example, if your double foobar
is equal to 3.5
, defining it as an int will round it down to 3
.
double foobar = 3;
long long int num = foobar;
if (foobar == num) {
//whole
} else {
//not whole
}
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
A concise version of Pepe's answer
bool isWhole(double num)
{
return num == static_cast<int>(num);
}