payalpr2002
asked on
Comparing 2 numbers of type "double" in C
Hi,
I have following code snippet. When i run it it gives strange result.
double Amount1=0,Amount2=720.05;
Amount1=65.45;
Amount1+=60.00;
Amount1+=579.60;
Amount1+=15.00;
if(Amount1>Amount2)
printf("Amount1 is greater than Amount2\n",f1,f2);
else
printf("The Amounts are equal.");
Expected Ans is: The Amounts are equal.
But it is giving result as "Amount1 is greater than Amount2"
Actually both amounts have same value - 720.05. Then how C treats Amount1 greater than Amount2?
Can some one explain why this is happening & what's the solution to get correct result?
I have following code snippet. When i run it it gives strange result.
double Amount1=0,Amount2=720.05;
Amount1=65.45;
Amount1+=60.00;
Amount1+=579.60;
Amount1+=15.00;
if(Amount1>Amount2)
printf("Amount1 is greater than Amount2\n",f1,f2);
else
printf("The Amounts are equal.");
Expected Ans is: The Amounts are equal.
But it is giving result as "Amount1 is greater than Amount2"
Actually both amounts have same value - 720.05. Then how C treats Amount1 greater than Amount2?
Can some one explain why this is happening & what's the solution to get correct result?
ASKER
How to round a decimal number to a fixed number of digits before doing the comparison? i think it will then compare properly & i will get correct result.
ASKER
Can u suggest me a good link which will explain the binary decimal mathematics - addition,comparison & how the decimal numbers are stored in memory?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Some theory:
http://illusivestudios.com/tutorials/fixed.html (fixed point)
http://www.nuvisionmiami.com/books/asm/workbook/floating_tut.htm (floating point)
http://illusivestudios.com/tutorials/fixed.html (fixed point)
http://www.nuvisionmiami.com/books/asm/workbook/floating_tut.htm (floating point)
try by type casting.
if((float)Amount1>Amount2)
ASKER
>You can multiply both numbers by 100 before comparing:
if ( ((int)(a*100.0)) == ((int)(b*100.0)) {
.....
}
This is really a good solution - very simple but works perfectly fine.
Thanks a lot!
if ( ((int)(a*100.0)) == ((int)(b*100.0)) {
.....
}
This is really a good solution - very simple but works perfectly fine.
Thanks a lot!
3.5 ---> 11.1 (3 + .5)
3.75 ---> 11.11 (3 + .5 + .25)
3.60 ----> 11.10011.... (3 + .5 + .0625 + 0.03125 + ....continues)
So, when converted back again to decimal, it is not the exact number. This error is increased when some operation are made to this number.
If you want no precision loss with few fractional digits, you can round your number to a fixed number of digits, before comparing.