0

Below is my code and program output:

#include <stdio.h>
int main()
{
float salary;
printf("Please enter the salary : ");
scanf("%f", &salary);
printf("Your Salary is : %f\n", salary);
}


desktop:~$ ./a.out 
Please enter the salary : 101.8889999
Your Salary is : 101.889000
desktop:~$ 

I tried many ways by entering random decimal values but sometime it printed correct values (as entered during scanf call) and sometimes it just prints something near to it. Why is it that the float variable values are not printing correct values as entered?

As per example above - if I enter 101.8889999 then the value saved in salary float variable is 101.889000?

I tried changing the last line as :

printf("Your Salary is : %10.9f\n", salary);

But still it gave below output:

Please enter the salary : 101.889000
Your Salary is : 101.888999939

Please enter the salary : 10.999999999
Your Salary is : 11.000000000

Which is the correct value to print float using printf and is it that float values may / may not be stored as exact values as entered in float variables?

Programmer
  • 8,303
  • 23
  • 78
  • 162
  • You might enjoy [this video](http://vimeo.com/7516539). Apparently, humans design precision that they can't possibly understand :) – Tim Post Aug 06 '14 at 17:22

1 Answers1

3

In C and in many other languages, floating point numbers are stored with a fixed number of bits (usually 32 or 64) so there is a limit to how much precision they can have, and there are only a finite number of numbers that can be exactly represented with a float. For all other numbers, the float can only store an approximation. You can see how many bits are used by printing the value of 8 * sizeof(float).

Additionally, floating point operations generally have rounding errors which makes them ill-suited for dealing with money.

If you are dealing with money, you might consider storing the values as an integer that represents the number of pennies, or the hundredths of a penny, or something like that.

David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • 1
    My bank is hiring. Maybe we could work out a ... deal ... or something. Because being down to my last $99.000000093 bucks is just depressing. – Tim Post Aug 06 '14 at 17:28
  • Thanks for the explanation, I get the issue with Floating / Double precession variables – Programmer Aug 07 '14 at 00:53