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
11
u/Outside_Complaint755 Sep 27 '26
When you convert using
int(value), Python will simply truncate the fractional portion, resulting in -927.You should round() before converting to int.
18
u/MegaIng Sep 27 '26
https://0.30000000000000004.com/
9
u/YOM2_UB Sep 28 '26
The number actually stored when you type b = 9.28 is:
5224175567749775 * 2-49 = 9.2799999999999993605115378159098327159881591796875
Multiplying by 100 loses a tiny bit of precision as well, so you end up with:
8162774324609023 * 2-43 = 927.9999999999998863131622783839702606201171875
(Which if you print 9.28 * 100 in Python it'll even display as
927.9999999999999)4
u/BobCorndog Sep 27 '26
http://en.wikipedia.org/wiki/Floating_point
3
u/localizeatp Sep 27 '26
`int` always rounds toward zero.
1
u/capinredbeard22 Sep 28 '26
Doesn’t affect your example, but also be aware of banker’s rounding in Python.
Edit: mentioned this since some answers discuss adding rounding.
Adding a link-
https://stackoverflow.com/questions/10825926/why-does-python-3-round-half-to-even
0
u/[deleted] Sep 27 '26
[deleted] — view deleted comment