Math.floor() in JavaScript with Examples

Deepak Prasad

Math.floor() rounds a number down to the nearest integer in JavaScript. It is the method you use when you want to drop the fractional part and keep the lower whole number.

This method is common in pagination, array index calculations, and random number generation. If you also need the upward direction, Math.ceil in JavaScript is the direct comparison.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Round a number down with Math.floor()

Math.floor() always moves the value down to the next lower integer.

javascript
const num = 5.75;
console.log("floor-1:", Math.floor(num));
Output

You should see one line logging floor-1: 5.

This is the basic form you use when you only want the lower integer value.


Method 2: Use Math.floor() to count digits

A common trick is to pair it with Math.log10() for digit counting.

javascript
function getNumDigits(num) {
  return Math.floor(Math.log10(num)) + 1;
}

console.log("floor-digits:", getNumDigits(12345));
Output

You should see one line logging floor-digits: 5.

Use this when you need a rough count of digits for formatting or validation.


Method 3: Use Math.floor() for random integers

The common pattern is to scale Math.random() and then drop the fraction.

javascript
const randomNumber = Math.floor(Math.random() * 6) + 1;
console.log("floor-random:", randomNumber >= 1 && randomNumber <= 6);
Output

You should see one line logging floor-random: true.

This is the standard method for dice rolls, random indices, and bounded random values.


Summary

Math.floor() is the JavaScript rounding-down method. Use it for lower integer values, digit counting, and random integer generation when you want the fractional part removed.


Official documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains.

  • JavaScript
  • Web Design