views:

291

answers:

2

I'm trying to extract the integer and decimal parts of a floating point value, and I seem to be running into some strange rounding problems, due probably to the imprecise way floats are stored.

I have some code like this to extract the fractional part:

double number = 2.01;
int frac = int(floor(number * 100)) % 100;

However the result here instead of 1 comes out as 0. This seems to be because the original double actually gets stored as:

2.0099999...

However running sprintf seems to get such a conversion correct:

char num_string[99];
sprintf(num_string,"%f",number);

How is sprintf getting the correct answer while the above method does not?

+2  A: 
dirkgently
Thanks for pointing out my errors, I really should avoid writing such questions late at night.
Tristan Havelick
Were you able to fix it?
dirkgently
+1  A: 

I agree with dirkgently on using modf from math.h. But if you must do the juggling yourself, try this code. This should work around the problem you see.

int round(double a) {
    if (a > 0)
        return int(a + 0.5);
    else
        return int(a - 0.5);
}

int main()
{
    double number = 2.01;
    int frac = round((number - ((int)number)) * 100);
    printf("%d", frac);
}
m-sharp
The standard does not define _tmain().
dirkgently
agreed. edited the submission.
m-sharp