Odd behavior of int(x) in python
When running this program,
cost = 12
money = 12.51
change = money - cost
dollars = int(change)
change -= dollars
quarters = int(change / 0.25)
change -= quarters * 0.25
dimes = int(change / 0.1)
change -= dimes * 0.1
nickels = int(change / 0.05)
change -= nickels * 0.05
pennies = int(change / 0.01)
print("""Your change is:
%i dollars
%i quarters
%i dimes
%i nickels
%i pennies
""" % (dollars, quarters, dimes, nickels, pennies))
The output is
Your change is:
0 dollars
2 quarters
0 dimes
0 nickels
0 pennies
Why is pennies 0? I've tried printing pennies separately, same thing
happens. I know for certain as well that change / 0.01 is equal to 1.0.
For some reason, it seems that int(1.0) is equal to 0. Obviously, it's
not. Maybe 1.0 is a floating point number and gets floored to 0?
Sidenote: Removing int function on pennies and replacing with %.0f pennies
works.
I guess this is exactly what people talk about when they say not to use
floating point numbers when working with money. :)
No comments:
Post a Comment