Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   how to compare decimals in c programming (http://www.go4expert.com/forums/compare-decimals-c-programming-t25837/)

jose_peeterson 19May2011 18:46

how to compare decimals in c programming
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??

xpi0t0s 20May2011 12:08

Re: how to compare decimals in c programming
Exactly the same way you compare integers:

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

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 10Jun2011 13:40

Re: how to compare decimals in c programming
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.

xpi0t0s 10Jun2011 15:30

Re: how to compare decimals in c programming
Yep, that's another way.

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 10Jun2011 15:34

Re: how to compare decimals in c programming
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.

All times are GMT +5.5. The time now is 05:59.