[Tutor] How did this decimal error pop up?

Jim Mooney cybervigilante at gmail.com
Tue Apr 16 19:43:57 CEST 2013


I was doing a simple training prog to figure change, and wanted to avoid
computer inaccuracy by using only two-decimal input and not using division
or mod where it would cause error. Yet, on a simple subtraction I got a
decimal error instead of a two decimal result, as per below. What gives?

cost = float(input('How much did the item cost?: '))
paid = float(input('How much did the customer give you?: '))
change = paid - cost

*#using 22.89 as cost and 248.76 as paid*

twenties = int(change / 20)
if twenties != 0:
  twentiesAmount = 20 * twenties
  change = change - twentiesAmount
  *#change is 5.8700000000000045, not 5.87 - how did I get this decimal
error when simply subtracting an integer from what  should be a
  #two-decimal amount?
*  print(twenties, ' twenties')
  print(change)

#and so forth for the rest of the change

-- 
*Jim Mooney

If you shoot a child you're a bad guy. If you splatter forty children
across a wall with a bomb, you're a heroic, manly Top Gun with gleaming Tom
Cruise teeth. The moral is you'll get laid more if you snuff a lot of
children than if you only snuff a few.*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130416/ea5ea55b/attachment.html>


More information about the Tutor mailing list