Rounding With Math.round()
In this lesson, you ported the batch planner’s bags and cost lines, and found where JavaScript’s rounding parts ways with Python’s.
- JavaScript has no
mathmodule to import. Its math functions live onMath, with a capital M, a built-in global object that’s always there. Watch out: JavaScript’s form of the import,import math from "math", stops the file withERR_MODULE_NOT_FOUNDbefore any line runs. math.ceil()becomesMath.ceil(), which rounds up as Python’s does, so the 37.5 kg order needs 150 bags, though it gives back a plain number, not anint.Mathalso holdsMath.sqrt()andMath.PI(Python’smath.pi), andMath.random()for random numbers.- Python’s built-ins
round(),abs(),max()andmin()move ontoMathtoo. Watch out:abs()orround()on its own is aReferenceError. Math.abs(-75)is75, andMath.max(12, 8, 17.5)andMath.min(12, 8, 17.5)are17.5and8. They take separate values; finding the largest in an array comes later.Math.round()always rounds to a whole number: unlike Python’sround(), it has no place for a number of decimals. Where Python finds no place for an argument, it raises aTypeError, but JavaScript doesn’t check how many arguments you pass, andMath.round()reads only the first. SoMath.round(greenKg * GREEN_PRICE_PER_KG, 2)gives326, and the planner printsGreen coffee: €326where Python printsGreen coffee: €326.47.- To round to cents, scale up, round, and scale back:
Math.round(rawCost * 100) / 100. Times 100, the cost is32647.058823529413cents,Math.round()makes that32647, and dividing by 100 gives326.47. - That rounds for further calculation. Showing a price with exactly two decimals is a separate job, for a later lesson.
- Watch out for exact halves:
Math.round()rounds a half up, toward positive infinity, soMath.round(2.5)is3where Python’sround(2.5)is2. Below zero,Math.round(-2.5)is-2; Python’sround(-2.5)is-2too, but only because-2is even. On the cents line, an exact half-cent splits the same way:0.125rounds to0.13in JavaScript and0.12in Python.
Here are just the two new lines and the settings they use; the batch lines stay where they are:
const WEIGHT_LOSS = 0.15;
const BAG_G = 250;
const GREEN_PRICE_PER_KG = 7.4;
const orderKg = 37.5;
const greenKg = orderKg / (1 - WEIGHT_LOSS);
const bags = Math.ceil((orderKg * 1000) / BAG_G);
const rawCost = greenKg * GREEN_PRICE_PER_KG;
const cost = Math.round(rawCost * 100) / 100;
console.log(`Bags: ${bags}`);
console.log(`Green coffee: €${cost}`);