Start learning free

LESSON 161 OF 173 · BACKEND: BACKEND WITH AI

Money in Floats

Practice

A computer stores decimal numbers, floating-point doubles, in binary. In binary, 0.1 has no exact value, just as 1/3 has none in decimal (0.333...). So in Java 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, in an int 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 doubles. A customer who bought one sticker and one pencil was told to pay 0.30000000000000004:

static final Map<String, Double> PRICES = Map.of("sticker", 0.10, "pencil", 0.20, "eraser", 0.45, "postcard", 1.15);

@PostMapping("/cart/total")
Object cartTotal(@RequestBody Map<String, Object> data) {
    List<Map<String, Object>> items = (List<Map<String, Object>>) data.get("items");
    double total = 0.0;
    for (Map<String, Object> item : items) {
        total = total + PRICES.get(item.get("product")) * (int) item.get("quantity");
    }
    return Map.of("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 doubles and 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 as a Map<String, Integer> in cents (sticker 10, pencil 20, eraser 45, postcard 115) and rewrite cartTotal: add up each item's price times its quantity in an int, and answer {"total_cents": ...}.


Assignment
Follow the Coding Tutorial to rewrite the price list and cartTotal so every amount is a whole number of cents.


Hint
Keep every number whole, from the price list to the total: int total = 0, never a double. Dividing by 100 is for whoever shows the price to a person, not for this method.


STEP 1 OF 6
    Ctrl + Enter to check