Floating point error in C

Hi,
see the simple code below

double i;
i=8080.9940;
printf(" val :%.30f\n",i);

output i m getting is
val :8080.993999999999700000000000000
when i m expecting
val :8080.9940

what happens?how can i avoid it?
thanks...

Floating point numbers have a complex representation using base 2 rather than base 10. Scientific notation is close enough to understand what is happening. With scientific notation, we want a number between 1 and 10 multiplied by a power of 10: 8080.9940 = 8.0809940 * 10^3 and we can check that out with bc:

$ bc
bc 1.03 (Nov 2, 1994)
Copyright (C) 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
8.0809940 * 10^3
8080.9940000
^D$

But now we need to do that in binary... We want a number between 1 and 10 in binary (which means 1 and 2 in decimal) that can be multiplied by a power of 10 in binary to yield the decimal number 8080.9940. Fortunately, you picked an easy number! It's is obvious that dividing it by 4096 will yield a number between 1 and 2. So let's use bc to do this...

$ bc -l
bc 1.03 (Nov 2, 1994)
Copyright (C) 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
obase=2
scale=40
8080.9940/4096
1.111110010000111111100111011011001000101101000011100101011000000100\
0001100010010011011101001011110001101010011111101111100111011011001
l(4096)/l(2)
1100.000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00
obase=10
ibase=2
1.1111100100001111111001110110110010001011010000 * 10^1100
8080.9939999999478459358215332031250000000000000000
1.11111001000011111110011101101100100 * 10^1100
8080.99399995803833007812500000000000000

Now repeat the last operation, but replace 1.11111001000011111110011101101100100 with some other close-by binary number. No matter what you try, you cannot get exactly 8080.9940 Floating point numbers are bit more complex than this, but the exact same issue arises with them. There is no way to exactly represent 8080.9940 as a floating point number.

Hi,

You can try this code and will give the exact output which you are expecting

double i;
i=8080.9940;
printf(" val :%.4f\n",i);

Why because if you given %.30f it will consider 30 digit for fraction value so instead of %.30f we can use %.4f.

Let me know in case of any dificulties

Regards,
MPS