# Thread: modf function doesn't work properly

1. ## modf function doesn't work properly

I'm trying to store all digits of a decimal number.I have decided to use modf for this purpose.My code segment is;
Code:
```struct high_precision scan_high(int *j)
{
int i,a;
struct high_precision mynum;
double num1, fracpart, intpart;
printf("Enter the values> ");
scanf("%lf", &num1);
if( num1 < 0 )
mynum.sign = -1;
else
mynum.sign = 1;
num1 = fabs(num1);
fracpart = modf(num1, &intpart);
if ( intpart > 0 && intpart < 10 )
a = 1;
while( intpart == 0 ) {
fracpart *= 10;
fracpart = modf(fracpart, &intpart);
a -= 1;
}
for(i=0;fracpart > 0 && intpart != 0;i++){
if( intpart > 0 ){
mynum.digits[i] = intpart;
}
fracpart *= 10;
fracpart = modf(fracpart, &intpart);
}
*j = i;
mynum.decpt = a;

return(mynum);
}```
But somehow it doesn't work as I want.For instance;

Code:
```Enter the values> 0.009876
0.876000 9.000000
0.760000 8.000000
0.600000 7.000000```
It must stop at this line.But, it is continuing to count;
Code:
```1.000000 5.000000
1.000000 9.000000
1.000000 9.000000
1.000000 9.000000
1.000000 9.000000
1.000000 9.000000
0.999998 9.000000
0.999977 9.000000
0.999767 9.000000
0.997669 9.000000
0.976694 9.000000
0.766942 9.000000
0.669420 7.000000
0.694198 6.000000
0.941983 6.000000
0.419827 9.000000
0.198267 4.000000
0.982671 1.000000
0.826707 9.000000
0.267069 8.000000
0.000000 2.000000
0.000000 0.000000```
I guess that's because floating-point numbers.
help me to solve this problem...

2. Yep, it's a floating point issue. Read this for a thorough explanation of floating point issues: What Every Computer Scientist Should Know About Floating-Point Arithmetic.

I added the following line right after the scanf. I think it will explain what's happening: printf("The real floating point number is: %.40f\n", num1); Notice how those digits somewhat match the intpart column in your printout, but there is some distortion from all your multiply-by-10 statements. That distortion is because multiplying by 10 doesn't map well to "moving the decimal point" since the internal representation is base 2, not base 10.

I would suggest using an existing big num library if possible (GMP comes to mind). They're far more complete, better tested and usually pretty optimized. If that isn't an option, consider reading in the input as a string (using fgets), since that's basically an array of digits, which is how you are storing it. Besides, scanf is prone to overflowing the type of where you're storing it (num1), so it's not well suited for big num use.