Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check double variable if it contains an integer, and not floating point

What I mean is the following:

  double d1 =555;   double d2=55.343 

I want to be able to tell that d1 is an integer while d2 is not. Is there an easy way to do it in c/c++?

like image 253
vehomzzz Avatar asked Oct 05 '09 18:10

vehomzzz


People also ask

Can a double variable store an integer?

Many compilers of programming languages use this standard to store and perform mathematical operations. This code may be justified when it is executed on a 32-bit system because the type double has 52 significant bits and can store a 32-bit integer value without loss.


1 Answers

Use std::modf:

double intpart; modf(value, &intpart) == 0.0 

Don't convert to int! The number 1.0e+300 is an integer too you know.

Edit: As Pete Kirkham points out, passing 0 as the second argument is not guaranteed by the standard to work, requiring the use of a dummy variable and, unfortunately, making the code a lot less elegant.

like image 82
avakar Avatar answered Oct 18 '22 05:10

avakar