how to compare decimals in c programming

jose_peeterson's Avatar, Join Date: May 2011
Contributor
hey guys i am a newbie, can anyone please tell me how to compare decimals in c. i know you can compare integers but decimals??
thanks
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Exactly the same way you compare integers:
Code:
float a=3.141, b=2.718;
if (a==b) // do something.
However there's a gotcha. Decimal conversions to binary are not precise. Try converting 0.1 yourself into binary and see what happens. The computer can only use fixed precision; it has no way of representing repeating decimals.

So floating point comparisons need to take this inaccuracy into account, e.g.:
Code:
int a=3.141, b=2.718;
if (a-b<0.005 || b-a<0.005)
  //  then assume it matches.
and of course you should set the value 0.005 according to the precision needed by the program. So if it's a banking program then you could set it to 1/100th of the smallest currency, for example if you're using British Sterling, where 100 pence make a pound, then you could check for less than 0.0001 (maybe). It really depends how much accuracy you need. If you need it to be exact then you need to use integers, so for instance you could store Sterling values as numbers of pence, or numbers of tenths of pence etc.
jose_peeterson's Avatar, Join Date: May 2011
Contributor
hey thanks a lot,

but i found a way around it just simply by multiply the decimal by a few thousands provided the decimal is ending.e.g compare 2.562715 and 2.562716 then i would multiply buy 1000000 then assign it to 2 integers then compare.
i am just a newbie. Thanks for your method
please keep in touch.
thanks
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Yep, that's another way.
Code:
if *(int)(a*1000)==(int)(b*1000))
  // then it matches
is just as good as the first example I posted. You'll need to make sure you have the headroom though, if you're comparing floats up to 2147483.647 then you'll be OK, but anything over that and you'll overflow the int which will produce invalid results. You mentioned "a few thousand" so if that's 10,000 then your maximum float values can be 214748.3647, which is less than a quarter million.
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
2147483647 isn't some random number I just pulled out of the air by the way, it's the most you can store in a signed 32-bit int. 2^31-1=2147483647.

And just in case you're thinking overflow might not be too bad, well, 2147483647+2=-2147483647.
Stick that up a maths major if you like watching them run away screaming.