Link to home
Start Free TrialLog in
Avatar of payalpr2002
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?
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

binary decimal mathematics is not an exact science. So, some values that are exact in decimal form, are not exact when machine converts to a binary. In fact, fractional  portion of a number in binary is the sum of fractions of powers of 2

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.
Avatar of payalpr2002
payalpr2002

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.
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
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

 try by type casting.
 
   if((float)Amount1>Amount2)
>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!