Start learning free

LESSON 161 OF 173 · BACKEND: BACKEND WITH AI

Money in Floats in JavaScript

Practice

A computer stores numbers with decimals, floats, in binary. In binary, 0.1 has no exact value, just as 1/3 has none in decimal (0.333...). So in JavaScript 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:

const PRICES = { sticker: 0.10, pencil: 0.20, eraser: 0.45, postcard: 1.15 };

app.post("/cart/total", (req, res) => {
  const items = req.body.items;
  let total = 0;
  for (const item of items) {
    total = total + PRICES[item.product] * item.quantity;
  }
  res.json({ 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 the function of the /cart/total route: add up each item's price times its quantity, and answer {"total_cents": ...}.


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


Hint
Keep every number whole, from the price list to the total: prices in cents, and a total that starts at 0. Dividing by 100 is for whoever shows the price to a person, not for this route.


STEP 1 OF 6
    Ctrl + Enter to check

    Ai Float Money in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free