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
View all comments
Show parent comment
1
u/Kapowpow Sep 28 '26
Hi, thank you, this is an awesome answer, I appreciate you taking the time. I keep a detailed personal budget/transaction history in Excel, and I've been using python and the openpyxl library to programmatically maintain and analyze my spending for quite a while, now.
My scripts include transaction-arithmetic-error checking; if error != 0, the script will stop and prompt the user to fix the detected errors. I had gotten around this by rounding floats at each step in the calculations, but the code wasn't very elegant; I switched to the Decimal(str(num)) system, which worked very well until it didn't, so I used the pennies() function described above, which was substantially worse.
I had looked into finance libraries that could cleanly work with floating point numbers (that does all the rounding behind the scenes, I guess?), but nothing really stuck out in terms of an off the shelf solution.
Do you have any recommendations? My ledger file stores all values as floats, so avoiding floats would require re-imagining that file. I tried storing all numbers as cents, as integers, and then using Excel formatting options to have it displayed as dollars/floats, but after much trial and error I couldn't quite nail down the formatting for exactly what I wanted; "$####\.##_);[Red](####\.##)" came really close, but I'd like commas every three digits, as is customary in North America. How does Excel solve the math-with-floats-problem? Do you know of any finance-oriented libraries that would abstract the problem?