Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Testing integer vs float value

Status
Not open for further replies.

chaawuu

Programmer
Oct 16, 2002
1
US
suppose i have:
int a = 12;
int b = 19;
float c = a / b;

The value for c is a float. How would I test whether or not it was an integer, or a whole number?
 
You can use the floor() function:

first you need to #include "math.h" in the appropriate header file.

What floor() does is return the integer value of a double/float.

Therefore:

double d = 123.456;
double e = floor(d); // the value of e is now 123.0

So... in this context, you can check whether a double/float has an integer value:

if (d == floor(d))
{
// we know that d is a whole integer
}

To get the fractional part of a double/float you could:

double d = 123.456;
double fPart = d - floor(d);

// the value of fPart is now 0.456


A similar function called ceiling() will return the next highest integer value above a double/float:

double d = 123.456;
double c = ceiling(d);

// the value of c is now 124.0


Now, just to add the icing on the cake so to speak, try to use doubles instead of floats. They tend to be more accurate.

 
hi,

another trik is to test the remainder of integer division:

if( a%b )
there is a remainder


or

int a,b,x
float f
....
x=a/b
f=(float)a / (float)b
if( (float)x!=f )
f had decimal part


bye
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top