[Tutor] Ingenious script (IMO)

Kent Johnson kent37 at tds.net
Sat Aug 11 15:05:44 CEST 2007


Dick Moores wrote:
> I was just about finished with a script that would tell the clerk how 
> to give the change to the customer, when I discovered that the above 
> script computes the wrong amount of change in certain situations. It 
> works fine if the customer tenders only bills and no change, but 
> that's not realistic. For example, if the cost is $1.78 the customer 
> may well tender $2.03 so he can get a quarter back rather than 2 
> dimes and 2 pennies. But the script in that case will compute change 
> of 24 cents!  Try it out. I've put the same script on the web, but 
> deleted the line that I'd left in by mistake, "print coinCount".

The problem is that
int(100 * float("2.03"))
is 202, not 203, because the float representation of 2.03 is actually 
2.0299999999999998.

The same problem occurs if you enter 2.03 as the cost and 3.00 as the 
amount tendered; it computes change of $0.98.

Use int(round(100 * float("2.03"))) to get the correct amount.

Kent


More information about the Tutor mailing list