A computer stores decimal numbers, floats, in binary. In binary, 0.1 has no exact value, just as 1/3 has none in decimal (0.333...). So in Python 0.1 + 0.2 is 0.30000000000000004, a tiny bit more than 0.3. For money, that's a bug. Store amounts as whole numbers of the smallest unit, cents, instead: 19.99 euros is 1999 cents, and 1999 + 1 is exactly 2000.
An AI assistant wrote the cart total for the shop's stationery corner, with the prices in euros, as floats. A customer who bought one sticker and one pencil was told to pay 0.30000000000000004:
PRICES = {"sticker": 0.10, "pencil": 0.20, "eraser": 0.45, "postcard": 1.15}
@app.post("/cart/total")
def cart_total():
items = request.get_json()["items"]
total = 0.0
for item in items:
total = total + PRICES[item["product"]] * item["quantity"]
return jsonify({"total": total})
For 3 postcards it said 3.4499999999999997, a little less than the real price. Some totals came out right, like 3 postcards and 2 erasers (4.35), and that's how the bug got past a quick try. When AI code works with money, look for floats.
The client sends the cart as JSON, like {"items": [{"product": "sticker", "quantity": 3}]}. Your version must answer whole cents:
POST /cart/total {"items": [{"product": "sticker", "quantity": 1}, {"product": "pencil", "quantity": 1}]} → 200 {"total_cents": 30}
POST /cart/total {"items": [{"product": "sticker", "quantity": 3}]} → 200 {"total_cents": 30}
POST /cart/total {"items": [{"product": "postcard", "quantity": 3}]} → 200 {"total_cents": 345}
POST /cart/total {"items": [{"product": "postcard", "quantity": 3}, {"product": "eraser", "quantity": 2}]} → 200 {"total_cents": 435}
POST /cart/total {"items": [{"product": "sticker", "quantity": 7}]} → 200 {"total_cents": 70}
POST /cart/total {"items": []} → 200 {"total_cents": 0}
Your task: write the price list PRICES in cents (sticker 10, pencil 20, eraser 45, postcard 115) and rewrite cart_total: add up each item's price times its quantity, and answer {"total_cents": ...}.
Assignment
Follow the Coding Tutorial to rewrite the price list and cart_total so every amount is a whole number of cents.
Hint
Keep every number whole, from the price list to the total: start the total at 0, not 0.0. Dividing by 100 is for whoever shows the price to a person, not for this function.
Free plan: 30 tutor messages. PRO is unlimited.
