In the following code:
the value for integer BAR is set to 178 rather than 179. I imagine this is an issue of rounding. How do I fix this?Code:float FOO; FOO = 1.79; int BAR = FOO * 100;
Thanks so much!
In the following code:
the value for integer BAR is set to 178 rather than 179. I imagine this is an issue of rounding. How do I fix this?Code:float FOO; FOO = 1.79; int BAR = FOO * 100;
Thanks so much!
Ahhh. why is it rounding?
Since 1.79 is not exactly representable inside the machine, you probably want to add a fudge factor. If you know it's supposed to be two decimal points, for instance, you could add 0.001 before multiplying by 100.
If you are trying to do exact arithmetic with decimal values (as in, say, money) that you really want to store the value in the correct units (pennies, instead of dollars) in an integer form.
Excellent, thank you
Actually the problem is that it's not rounding, it's truncating. If it were rounding then it would work. In fact, rounding is what you want to do here. Rather than adding an arbitrary fudge factor that you simply hope is big enough, I'd just add 0.5 before truncating to an integer.
Better yet as advised store the number in a kind of fixed point where the value is always multiplied by 100.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
That will work for this particular example; it will give unwanted results for different values of FOO (or different multiplication factors, for that matter).
Your other suggestion (eg dollars and cents as both integers, if working with currency) and iMalc's suggestions are more like it.
Another way, if rounding is wanted rather than truncating towards zero (which is what happens when FOO*100 is converted implicitly to an int) is to compute the nearest integer.
True. Technically. But the general problem is most often referred to as "round-off error".
http://en.wikipedia.org/wiki/Round-off_error
Interesting thought I just had. Instead of chopping the continuous binary representation, why wasn't it rounded - i.e. added a '1' to the last bit if the following to-be-chopped bit is a '1'. Would that have made the conversion back to base-10 any better? More accurate? I'll have to play with it.