Round down in Javascript with Math.floor

Math.floor is what you use to round numbers down to their nearest whole number. Making it so you end up with an integer. With negative numbers the number is brought to a lower value, so -3.21 would be rounded down to -4.

Math.floor(-3.21);
// Expected output -4

When rounding down regular numbers, it will look like this.

Math.floor(5.6);
// Expected output 5

Although this is probably a bad idea, Math.floor will convert your strings into numbers if it’s possible for example.

Math.floor("5.6");
// Expected output 5

However as you would expect, if you try an invalid string you’ll see this.

Math.floor("5.6!");
// Expected output NaN

Math.floor is 100% compatible with all browsers, because it’s been there from the very beginning, and there are no plans to remove it.

In the beginning, they wanted JavaScript to closely resemble Java, so the Math function was made, and static methods like Math.floor were set up so that it felt object oriented. Now so much of JavaScript could be object oriented, functional, or any other style, so it’s kind of fun.

The most common use of Math.floor in my life, the roll a dice function I always look up and use for generating random whole numbers. Here it is, it’s a good example of Math.floor being useful.

return Math.floor(Math.random()*6)