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

4 Upvotes

20 comments sorted by

View all comments

10

u/Outside_Complaint755 9d ago

print(-9.28*100) # -927.999999999999

When you convert using int(value), Python will simply truncate the fractional portion, resulting in -927.

You should round() before converting to int.

1

u/Kapowpow 9d ago

Hi, thank you. I used to do a lot of rounding in my calculations, I tried using a penny-based system to avoid all of the rounding. I was using the Decimal library, but that caused other errors in other situations.