Loading video player…

Counting Money in Cents

Counting Money in Cents

In this lesson, you ported the money lines of the invoice script. The Python keeps every amount in a Decimal built from text, rounds each café’s amount with quantize(Decimal("0.01"), rounding=ROUND_HALF_UP), and checks the month’s total against the web shop’s with ==. It prints Month total €1,303.20 matches the web shop.

  • JavaScript’s everyday number type is the same binary double as Python’s float, and there’s no decimal type. The line-by-line port writes Number() for Decimal(), the recipe Math.round(amount * 100) / 100 for quantize(), and === for ==.
  • The port prints the three amounts as Python does, €666.00, €172.80 and €464.40, but its check line reads Check the export: €1,303.20 here, €1303.20 in the shop.
  • Decimal("464.40") keeps exactly the digits you give it. A double stores the nearest binary fraction, 464.39999999999997726263, and each += rounds again, up or down, so monthTotal lands a hair below, at 1303.1999999999998. The shop’s Number("1303.20") is a different double, and === compares the doubles themselves, so it gives false.
  • The euro formatter rounds to two decimals for display, so both totals print as €1,303.20. It hides the error, but the value keeps it. Python’s floats give the same total in a += loop: Decimal is what made == safe.
  • The recipe rounds the stored double, so a half cent can go the wrong way: 1.005 is stored as 1.00499999999999989342, so Math.round(1.005 * 100) / 100 is 1, not 1.01, and (1.005).toFixed(2) is "1.00".
  • The JavaScript way is to count money in whole cents, as you count weights in grams. Convert the price text where it comes in with Math.round(Number(text) * 100): "18.50" becomes 1850.
  • Python’s int(Decimal(price) * 100) ported with Math.trunc() drops a cent: Number("18.40") * 100 is 1839.9999999999998, so Math.trunc() gives 1839, as int() would on a float, where Math.round() gives 1840.
  • Each order adds price cents times grams, a whole number of thousandths of a cent: Larder Lane’s first order is 1850 * 12600, 23310000. Where Python calls quantize(), divide by 1000 and round once per café with Math.round(amount / 1000). The sum is whole, so a half cent comes out as exactly .5, and for positive amounts Math.round() sends it up, as ROUND_HALF_UP does.
  • The month total is 130320 cents, and toCents("1303.20") is 130320 too, so === gives true. Divide by 100 only on the output line. Whole numbers stay exact up to 2 ** 53, far past any invoice.

Here are the money lines in cents, run on October’s three cafés and eight orders (the order IDs left out):

Language: JavaScript
const euros = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "EUR",
});
const toCents = (text) => Math.round(Number(text) * 100);
const cafes = [
  { name: "Larder Lane", pricePerKg: "18.50" },
  { name: "Bluebell Café", pricePerKg: "19.20" },
  { name: "Northside Kitchen", pricePerKg: "17.20" },
];
const orders = [
  { cafe: "Larder Lane", kg: 12.6 },
  { cafe: "Larder Lane", kg: 11.6 },
  { cafe: "Bluebell Café", kg: 4.8 },
  { cafe: "Northside Kitchen", kg: 9.7 },
  { cafe: "Bluebell Café", kg: 4.2 },
  { cafe: "Northside Kitchen", kg: 8.9 },
  { cafe: "Larder Lane", kg: 11.8 },
  { cafe: "Northside Kitchen", kg: 8.4 },
];

let monthTotal = 0;
for (const cafe of cafes) {
  const priceCents = toCents(cafe.pricePerKg);
  let amount = 0;
  for (const order of orders) {
    if (order.cafe === cafe.name) {
      const grams = Math.round(order.kg * 1000);
      amount += priceCents * grams;
    }
  }
  amount = Math.round(amount / 1000);
  monthTotal += amount;
  console.log(`${cafe.name}: ${euros.format(amount / 100)}`);
}
console.log(monthTotal === toCents("1303.20"), monthTotal);

Every amount comes out as Python’s, and the check is exact:

Language: Program Output
Larder Lane: €666.00
Bluebell Café: €172.80
Northside Kitchen: €464.40
true 130320

Next up is the exercise Check September’s Invoices. There, you’ll port the report’s first lines for September, so they match what the Python script prints.

00:00 In this lesson, you’ll port the invoice script’s money lines. The Python keeps every amount in a Decimal, built from the price as text. It adds price times kilos for each order.

00:13 Then quantize() rounds the amount to the cent, half up. Last, == compares the month’s total with the shop’s. Python prints each café’s amount, then a check line: the totals match.

00:28 The JavaScript port disagreed. It printed the same total twice, the second as the shop’s text, without the comma, and still said to check the export. Now you’ll find out why.

00:43 JavaScript’s everyday number type is the same binary double as Python’s float, and there’s no decimal type. The loops, the running total and the print line carry over, and euros is the euro formatter.

00:56 The port turns each Decimal() into a Number() call. The kilos are numbers already, so str() and Decimal() drop away.

01:04 For quantize(), it uses the usual recipe: it scales by 100, rounds with Math.round(), and divides back. And == becomes ===, as usual.

01:18 Run it, and JavaScript prints the three amounts as Python does. What’s in monthTotal when the check runs? Your turn: pause the video and predict.

01:34 monthTotal holds a hair less than 1303.2. So === says false, and the port lands on the check line.

01:46 Python’s Decimal keeps the digits you give it: 464.40 stays 464.40. A double stores the nearest binary fraction, and for 464.4, that’s a hair below.

02:00 Each += rounds again, up or down, as with the weights; here the total lands a hair below. The shop’s total is the double nearest 1303.2. === compares the doubles themselves, and they differ.

02:18 The euro formatter hides the difference: it rounds for display, but the value keeps its error. Python’s floats would do the same in a += loop: Decimal is what made == safe.

02:31 Watch out: the recipe rounds the stored double, so a half cent can go the wrong way. 1.005 should give 1.01, but it’s stored a hair below, so the recipe gives 1, and .toFixed(2) agrees.

02:48 The JavaScript way is the move you made with the weights: count in whole units, here cents. toCents() converts the price text where it comes in.

02:59 Number() reads the text, times 100 gives cents, and Math.round() lands on the nearest whole cent. So 18.50 becomes 1850. Watch out: Python’s int(Decimal(price) * 100), ported with Math.trunc(), drops a cent.

03:18 18.40 times 100 is a hair under 1840, so Math.trunc() gives 1839, as int() would on a float.

03:29 The weights turn into grams, as before. Then each order adds price cents times grams, in thousandths of a cent. For Larder Lane’s first order, that’s 23310000.

03:44 Every figure is a whole number now, and whole numbers multiply and add exactly.

03:52 Where Python calls quantize(), the port divides by 1000 and rounds once, with Math.round(), to a whole cent. The sum is whole, so a half cent comes out as exactly .5, and for positive amounts, Math.round() sends it up, as ROUND_HALF_UP does.

04:10 The month total adds the cafés’ cents. The check converts the shop’s total with toCents() too, so === compares cents with cents.

04:19 Euros come back only on the output line, divided by 100. Run it, and the check line matches Python’s. Whole numbers stay exact up to two to the power 53, far past any invoice.

04:37 JavaScript has no decimal type, so exact money means whole numbers. Convert prices to cents where the text comes in. Add and multiply whole numbers. Round with Math.round() once, on purpose.

04:53 Compare cents with ===, and divide by 100 only to print. Next up is Check September’s Invoices, an exercise. There, you’ll port the report’s first lines for September to match the Python’s.

Become a Member to join the conversation.