• Status: Solved
• Priority: Medium
• Security: Public
• Views: 422

# 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?
0
payalpr2002
• 3
• 3
1 Solution

Software ArchitectCommented:
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.
0

Author Commented:
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.
0

Author Commented:
Can u suggest me a good link which will explain the binary decimal mathematics - addition,comparison & how the decimal numbers are stored in memory?
0

Software ArchitectCommented:
> 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.

You can multiply both numbers by 100 before comparing:

if ( ((int)(a*100.0)) == ((int)(b*100.0)) {
.....
}
0

Software ArchitectCommented:
0

Commented:

try by type casting.

if((float)Amount1>Amount2)
0

Author Commented:
>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!
0

## Featured Post

• 3
• 3
Tackle projects and never again get stuck behind a technical roadblock.