floating point - Odd behavior of int(x) in python -


when running 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 pennies 0? i've tried printing pennies separately, same thing happens. know change / 0.01 equal 1.0. reason, seems int(1.0) equal 0. obviously, it's not. maybe 1.0 floating point number isn't 1 , gets floored 0?

sidenote: removing int function on pennies , replacing %.0f pennies works.

i guess people talk when not use floating point numbers when working money. :)

i know change / 0.01 equal 1.0

well, not quite. if try doing change / 0.01 directly python interpreter, returns 0.99999999999787 due floating point errors. naturally, if try converting int, it'll round down zero.

to avoid this, try 1 of 2 things. either try using decimal module python, avoid floating point errors these, or multiply change 100 @ beginning you're dealing integer values, not floating point numbers, , modify rest of code accordingly.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -