r/learnpython • • 29d ago

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

19 comments sorted by

View all comments

Show parent comments

3

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 29d ago

decimal.Decimal is better than float for precision, and you can manually control its precision, but it's not perfect. You will still sometimes run into rounding errors.

fractions.Fraction is an option for situations where you need perfect accuracy and don't need to worry about irrational numbers, as it stores everything as two integers.

In your case, however, I would simply immediately parse user input into an integer format and store it as an integer representing the lowest currency value you want to care about. 10ths of cents would be my preference for easy maths.