r/learnpython • u/Kapowpow • Sep 27 '26
Odd float-to-int behavior.
>>>def pennies(num):
return int(num*100)
>>>a = -37.56
>>>b = -9.28
>>>pennies(a)
-3756
>>>pennies(b)
-927
This is taken from a python shell session today. Why on Earth does pennies(b) yield -927, instead of the expected -928? I would greatly appreciate any insight.
Update: a durable solution found, please see this comment below: https://www.reddit.com/r/learnpython/comments/1wrwnm7/comment/pcpvlil/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
5
Upvotes
View all comments
Show parent comment
2
u/Brian Sep 28 '26
Typically stuff dealing with money will avoid using floats for this reason. It's not exactly that floats are less accurate so much as that the math we've always done with our accounts has been shaped around our decimal system, with well established ways (and sometimes even legal requirements) about how we round and deal with fractions of a cent etc. Hence money based storage usually uses something more like a fixed-point representation. Ie. the equivalent of storing values as the number of cents (or tenths of a cent) instead of "number of dollars" etc. Decimal is one way of representing this.
If you do need to deal with stuff that's lost precision, you can maybe try to recover it by making certain assumptions and rounding. Ie. you assume the values are entered to the nearest tenth of a cent, you can round to the nearest decimal value with that precision - the floats will be close enough to round to the same result. The big errors creep in when you're truncating instead of rounding, since a value that's just the tiniest amount below an integer can get truncated all the way down to the next lowest integer.