Change Due

Consider the penny. It’s one cent, which was once a worthy sum before the government devalued the currency to the point where trays of pennies linger unwanted on convenience store checkout counters across the land. Why not do away with the penny?

One solution proposed is to round down the purchase price to the nearest nickel, or 5 cent mark. But how would that work?

The stores probably want the rounding to take place on the total only. So if you buy $35.67 worth of chips and beer at the 7/11, you save a whopping 2 cents as the price is rounded down to $35.65.

What if instead, each item’s price were rounded down to the nearest nickel as the total is calculated? In that situation, the customer saves far more money. You can write code prove it.

Your task for this month’s Exercise is to code a convenience store simulation: Generate random prices for 15 items, each of which cost between $0.01 and $9.99. Tally the total of each item as well as the total of each item rounded down to the next nickel (5-cent mark) and tally that total as well. Display each item’s original and rounded price, the running original total, rounded total, and the savings.

Here’s sample output from my solution:

Item	Org.	Rounded
1	$2.54	$2.50
2	$7.09	$7.05
3	$3.90	$3.90
4	$9.91	$9.90
5	$0.81	$0.80
6	$7.50	$7.50
7	$2.62	$2.60
8	$9.76	$9.75
9	$0.30	$0.30
10	$6.71	$6.70
11	$0.21	$0.20
12	$5.79	$5.75
13	$0.31	$0.30
14	$4.24	$4.20
15	$5.32	$5.30
15 items original total $67.01
Rounded down total $66.70
Savings = 0.31

This Exercise is trickier than it appears. The big problem is how to craft the prices to avoid floating-point rounding errors.

For example, a rounding error would be evident if you attempt to round down the value $4.57 to the nearest nickel but instead you see the value $4.56. As a hint, you can avoid this type of error if you’re careful how the original prices are created.

Click here to read my solution, though please try this Exercise on your own before checking what I’ve done.

Leave a Reply