Getting the fractional part of a double value in integer without losing precision

Atul Kumar Verma picture Atul Kumar Verma · Jun 23, 2013 · Viewed 11.4k times · Source

i want to convert the fractional part of a double value with precision upto 4 digits into integer. but when i do it, i lose precision. Is there any way so that i can get the precise value?

#include<stdio.h>
int main()
{
    double number;
    double fractional_part;
    int output;
    number = 1.1234;
    fractional_part = number-(int)number;
    fractional_part = fractional_part*10000.0;
    printf("%lf\n",fractional_part);
    output = (int)fractional_part;
    printf("%d\n",output);
    return 0;
}

i am expecting output to be 1234 but it gives 1233. please suggest a way so that i can get desired output. i want the solution in C language.

Answer

Christoph picture Christoph · Jun 23, 2013

Assuming you want to get back a positive fraction even for negative values, I'd go with

(int)round(fabs(value - trunc(value)) * 1e4)

which should give you the expected result 1234.

If you do not round and just truncate the value

(int)(fabs(value - trunc(value)) * 1e4)

(which is essentially the same as your original code), you'll end up with the unexpected result 1233 as 1.1234 - 1.0 = 0.12339999999999995 in double precision.

Without using round(), you'll also get the expected result if you change the order of operations to

(int)(fabs(value * 1e4 - trunc(value) * 1e4))

If the integral part of value is large enough, floating-point inaccuracies will of course kick in again.

You can also use modf() instead of trunc() as David suggests, which is probably the best approach as far as floating point accuracy goes:

double dummy;
(int)round(fabs(modf(value, &dummy)) * 1e4)