1

Possible Duplicate:
Floating point error in representation?

I have problem with this code

int cent;
int dollar ;
float cnt2dlr;
 //convert cnt to doloar ;
cnt2dlr=(cnt)/(100);

The problem is when cnt = 175, cnt2dlr = 0.17,444444 and not 0.17,5

Any help?

Community
  • 1
  • 1

3 Answers3

7

Floating point numbers are often inexact. There is nothing you can do about it.

Your code is a good illustration of why you should not use floating point numbers for calculations involving money. Just because currency values have a decimal point does not make money a floating point quantity. Floating points should be used for quantities which vary infinitesimally, like temperature or speed, not for quantities which vary in chunks, like money.

john
  • 7,897
  • 29
  • 27
  • But 32 bit floats still have more precision than that... I find it odd that it's off by so much. – CookieOfFortune Nov 07 '12 at 16:56
  • @CookieOfFortune Very true, but its not real code that was posted, so who can say. And if he's really converting cents to dollars by dividing by 1000 then his program has other problems. – john Nov 07 '12 at 16:58
  • Not disagreeing with you, but 24 bits of precision for 32 bit floats means the number should be really close to: 2936013/2 ^ 24 = 0.17500001192 – CookieOfFortune Nov 07 '12 at 17:07
1

Floating point numbers are not exact representations. They are approximations, so you cannot guarantee much precision. Read What Every Computer Scientist Should Know About Floating-Point Arithmetic

To increase the precision of the numbers, consider using a 64-bit double instead of a 32-bit float.

Doug T.
  • 64,223
  • 27
  • 138
  • 202
1

I am a bit puzzled. If you mean (cent) instead of (cnt), then

cnt2dlr=(cent)/(1000);

(note the e in cent) is an int / int division, and 175 / 1000 should return int 0.

Do you get the same result if you do, eg

cnt2dlr=(cent)/(1000.0);

note the decimal point.

Alf
  • 41
  • 2