The JavaScript Math.floor() method
The Math.floor() method rounds a number down to the nearest integer. Math.floor(4.9) is 4, and Math.floor(-4.1) is -5 — it always goes toward negative infinity. It's the rounding partner of Math.random() for generating whole numbers.
Overview
Math.floor() always rounds down to the nearest whole number. 4.9 becomes 4; 4.1 also becomes 4. The decimal part is simply dropped for positive numbers. You'll see it most often paired with Math.random() to turn a random decimal into a random integer.
The subtlety is negatives. "Down" means toward negative infinity, not toward zero, so Math.floor(-4.1) is -5, not -4. If you instead want to chop off the decimal and keep heading toward zero, that's Math.trunc(). The two agree on positive numbers and differ on negatives.
It sits in a family of four: Math.floor() rounds down, Math.ceil() rounds up, Math.round() rounds to the nearest, and Math.trunc() just drops the decimals. Reach for floor when you specifically need the lower bound — page counts, grid positions, splitting items into rows.
Syntax
Math.floor(4.9) // 4
Math.floor(4.1) // 4
Math.floor(-4.1) // -5 (toward negative infinity)
Parameters
The Math.floor() method accepts the following parameters.
| Parameter | Description |
|---|---|
x |
The number to round down to the nearest integer. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const total = 23, perPage = 10;
const pages = Math.ceil(total / perPage); // round up for page count
const full = Math.floor(total / perPage); // full pages only
document.getElementById('out').textContent =
'pages needed: ' + pages + '\n' +
'full pages: ' + full; // pages needed: 3 / full pages: 2
</script>
Best practices
- Use
Math.floor()with Math.random() to produce random integers. - For negatives, remember it rounds toward negative infinity — use
Math.trunc()to drop decimals toward zero instead. - Pick the right family member:
floor(down),ceil(up), round (nearest). - It returns an integer but still a
numbertype — no separate integer type is involved.
Frequently asked questions
What does Math.floor() do?
Math.floor(4.9) is 4.What is the difference between Math.floor() and Math.round()?
Math.floor() always rounds down; Math.round() rounds to the nearest integer (0.5 rounds up).Why does Math.floor(-4.1) give -5?
-4), use Math.trunc().What is the difference between Math.floor() and Math.trunc()?
floor() rounds down (more negative) while trunc() just removes the decimal (toward zero).