Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if a variable is a whole number? C++

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";
else
    cout << "Not whole";

How would I do this?

like image 505
Billjk Avatar asked Mar 08 '12 04:03

Billjk


2 Answers

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";
like image 122
laurent Avatar answered Oct 04 '22 01:10

laurent


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;
like image 43
Pepe Avatar answered Oct 04 '22 01:10

Pepe