-1

When I wrote a simple program to read and print a number using float, I came across some unexpected results.

In the following program when I entered a number 100.62, the result I got was 100.620003. Only upto eight digits the value showed correctly. Even when I tried different numbers the issue persisted. Why is this? Is there a way to overcome this problem other than by limiting the decimal points.

And also is there a way to print a digit as it is? ie; if I enter 100.62 it should print 100.62 and if enter 100.623 it should print 100.623 (not 100.620000 and 100.623000).

int main (void)
{
    float i;
    printf ("Enter a number : ");
    scanf ("%f", &i);
    printf ("You entered the number : %f", i)
    return 0;
}
user4520
  • 3,401
  • 1
  • 27
  • 50
  • 2
    If you only want to print significant digits, try `%g`. Also: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – user4520 Nov 01 '15 at 07:57
  • 3
    This is how floating-point values work on computers. An explanation can be found here: [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Thomas Padron-McCarthy Nov 01 '15 at 08:04

2 Answers2

1

This issue comes from how computers handle the float values.

One way to overcome this problem is stopping using float and deal the numbers as decimal data.

To print a digit as it is, just read input as a string and print it. This method is very simple and can support difficult inputs such as 1e-10000 or 1.00000.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
-1

As far as I know, the C always display those complete digits of float in default.

If you want to display custom decimal points, you should try using ".x" before the f notation. X is the total number that you want to show after the dot. For example:

float i;
printf ("Enter a number : ");
scanf ("%f", &i);
printf ("You entered the number : %.2f", i)
return 0;

this will result 2 numbers after the dot. If you input 100.62, it will show as 100.62. However, this is static. I mean, if you input 100.623, it will show 100.62, not 100.623. You should know exactly how many numbers after dot that you want to show.

Helen
  • 105
  • 2
  • 12
  • That will work for only float point nubers having `2` digits after decimal . Use `%g` spcifier for general case . – ameyCU Nov 01 '15 at 08:03
  • yes, I have said earlier that you should use .x to specify how many numbers (x) you want after the dot. Anyway thanks for your info. – Helen Nov 01 '15 at 08:19