int() conversion of float in python -


i conversting float integer in below code. , resultant output not correct nickels.

code:

actual = 25 paid = 26.65 cents = (paid-actual)*100 quarters = int(cents/25) cents = cents %25 dimes = int(cents/10) cents = cents %10 nickels = int(cents/5) print quarters, dimes, nickels,cents print 5.0/5,int(5.0/5) 

ouput:

6 1 0 5.0 1.0 1 

expected output

6 1 1 5.0 1.0 1 

if explicitly int(5.0/5) 1 , when same done assigned variable in code, 0 . not sure why. can explain ?

floating point numbers not guaranteed spot on number expect, barely off, 5.0 might 4.999... , since int() truncates/rounds down, error.

many banks give on floating point issue , work $1.00 = 100 advise same, this:

actual = 25 paid = 26.65 cents = int(round(paid*100)) #turns 26.65 2665 before float math dollars = cents / 100 cents %= 100 quarters = cents / 25 cents %= 25 dimes = cents / 10 cents %= 10 nickels = cents / 5 print quarters, dimes, nickels,cents print 5.0/5,int(5.0/5) 

note outputs 2 1 1 5 because that's 2 quarters, 1 dime, , 1 nickel = $.65

typically want round late possible maintain precision, when working money, think working entirely ints makes nightmare of floats go away faster.

also, since using 2.6, need cast int() because round() doesn't return integer until 3.1


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -