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

Show parent comments

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?

0

u/[deleted] Sep 27 '26

[deleted]

1

u/Kapowpow Sep 28 '26

Unfortunately, reproducing that error is a needle in a haystack, but other feedback has said that the source of the error is that I was using the Decimal(str()) system on numbers that started as floats. So, it sounds like the small value discrepancies were preserved in that transition.

I was comparing the sum of several Decimal(str(<float>)) numbers (x) to a reference number (y). The sum needed to be exactly equal to the reference number, so x - y == 0 needed to be satisfied. It typically wasn't an issue, but every so often, python wouldn't think the numbers matched, even though human arithmetic said that they do.

1

u/Swipecat Sep 28 '26

I was using the Decimal(str()) system on numbers that started as floats. So, it sounds like the small value discrepancies were preserved in that transition.

Yep.

Compare the result of

Decimal(1/7) * 7

with

1/Decimal(7) * 7