What exactly does Math.floor do?

No, in fact this line of code outputs 0:

 Math.floor(0.9);

Math.floor always rounds to the nearest whole number that is smaller than your input. You might confuse it with Math.round, that rounds to nearest whole number.

This is why this code always outputs 1 or 0, since input never gets to 2 or bigger:

Math.floor(Math.random()*2)

There’s actually three different rounding functions in JavaScript: Math.floor, its opposite Math.ceil and the “usual” Math.round.

These work like this:

Math.floor(0.1); // Outputs 0
Math.ceil(0.1); // Outputs 1
Math.round(0.1); // Outputs 0

Math.floor(0.9); // Outputs 0
Math.ceil(0.9); // Outputs 1
Math.round(0.9); // Outputs 1

Math.floor(0.5); // Outputs 0
Math.ceil(0.5); // Outputs 1
Math.round(0.5); // Outputs 1

Leave a Comment