r/learnpython • • 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

19 comments sorted by

View all comments

0

u/[deleted] Sep 27 '26

[deleted]

1

u/Kapowpow Sep 27 '26

Hi, thank you. I have used the Decimal library too, and it causes other problems, elsewhere. I even convert floating point numbers to strings before converting them to Decimal numbers. For example, Decimal(str(num1)) - Decimal(str(num2)) == 0 yields False, where num1 and num2 are Decimal sums from different sources, but are nominally equivalent.

Are there situations where the Decimal system also fails, similar to the floating-point system? To ask in a different way, does the Decimal system have any shortfalls, or will it correctly function universally?

3

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Sep 27 '26

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.