Replacing // With Math.floor()
In this lesson, you ported the batch planner’s full-batches line, the one that went quietly wrong in the course introduction, and found out why: JavaScript has no floor division operator.
- In Python,
green_kg // DRUM_KGdivides and rounds down. On a float it gives3.0, so the script wraps it inint()to get 3. - The port lives in
batch-plan.js, in the folderbatch-plan/, whosepackage.jsonholds{ "type": "module" }. - JavaScript has one number type, so the port has no
intto convert to, and drops theint()call. - In JavaScript,
//starts a comment, as#does in Python, and the comment runs to the end of the line. Soconst fullBatches = greenKg // DRUM_KG;is reallyconst fullBatches = greenKg, and it runs with no error. - Inside a call’s parentheses, the comment swallows the closing one. Then the file doesn’t run at
all: JavaScript reports
SyntaxError: missing ) after argument listbefore running a single line. - Division in JavaScript is always
/, which keeps the fraction.Math.floor()rounds the result down, as Python’s//does, and shares its name with Python’smath.floor().Mathholds JavaScript’s math functions, like Python’smathmodule, and it gets a lesson of its own soon. - Python’s
int()has two jobs. In the batches line it only turned3.0into 3, which JavaScript doesn’t need. Given decimals, it chops them off, and that’sMath.trunc():Math.trunc(greenKg / DRUM_KG)is 3, likeint(green_kg / DRUM_KG). For the planner’s weights, which are never negative, it gives the same 3 asMath.floor(). - Watch out: for values that can go below zero, such as a time offset, the two part ways.
Math.floor()goes down the number line andMath.trunc()goes toward zero. - So
Math.floor(-7 / 2)is -4, like Python’s-7 // 2, whileMath.trunc(-7 / 2)is -3, likeint(-7 / 2). - When you port
//, say which rounding you mean, above all when values can go negative:Math.floor()rounds down, as//does, andMath.trunc()chops the decimals, asint()does.
Here’s the port as first carried over from Python, with the // kept:
const WEIGHT_LOSS = 0.15;
const DRUM_KG = 12;
const orderKg = 37.5;
const greenKg = orderKg / (1 - WEIGHT_LOSS);
const fullBatches = greenKg // DRUM_KG;
console.log(`Batches: ${fullBatches} full`);