A computer stores decimal numbers, floats (float64 in Go), in binary. In binary, 0.1 has no exact value, just as 1/3 has none in decimal (0.333...). So when Go adds two float64 variables holding 0.1 and 0.2, it gets 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:
var prices = map[string]float64{"sticker": 0.10, "pencil": 0.20, "eraser": 0.45, "postcard": 1.15}
app.HandleFunc("POST /cart/total", func(w http.ResponseWriter, r *http.Request) {
var data Cart
json.NewDecoder(r.Body).Decode(&data)
total := 0.0
for _, item := range data.Items {
total = total + prices[item.Product]*float64(item.Quantity)
}
writeJSON(w, 200, map[string]float64{"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}]}, and the given Cart and Item types hold it. 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 package map prices as a map[string]int in cents (sticker 10, pencil 20, eraser 45, postcard 115) and rewrite the POST /cart/total handler: add up each item's price times its quantity, and answer {"total_cents": ...}.
Assignment
Follow the Coding Tutorial to rewrite the price map and the POST /cart/total handler so every amount is a whole number of cents.
Hint
Keep every number whole, from the price map to the total: total := 0 makes an int, while total := 0.0 would make a float64, and Go won't add an int price to it. Dividing by 100 is for whoever shows the price to a person, not for this handler.
Free plan: 30 tutor messages. PRO is unlimited.
