0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Math.floor in JavaScript: Simple Guide

Use Math.floor(number) in JavaScript to round a decimal number down to the nearest whole number. It always rounds towards negative infinity, so it removes the decimal part and returns the largest integer less than or equal to the given number.
📐

Syntax

The syntax for Math.floor is simple:

  • Math.floor(x) takes one argument x, which is the number you want to round down.
  • It returns the largest integer less than or equal to x.
javascript
Math.floor(x)
💻

Example

This example shows how Math.floor rounds different decimal numbers down to the nearest integer.

javascript
console.log(Math.floor(4.9));  // Output: 4
console.log(Math.floor(4.1));  // Output: 4
console.log(Math.floor(-4.1)); // Output: -5
console.log(Math.floor(-4.9)); // Output: -5
Output
4 4 -5 -5
⚠️

Common Pitfalls

One common mistake is expecting Math.floor to just remove the decimal part by truncating. But for negative numbers, it rounds down to the next lower integer, which means it can return a smaller number than expected.

For example, Math.floor(-4.1) returns -5, not -4.

javascript
console.log(Math.floor(-4.1)); // Outputs: -5 (rounds down)

// If you want to just remove decimals (truncate), use Math.trunc instead:
console.log(Math.trunc(-4.1)); // Outputs: -4
Output
-5 -4
📊

Quick Reference

MethodDescriptionExampleOutput
Math.floor(x)Rounds down to nearest integerMath.floor(4.7)4
Math.ceil(x)Rounds up to nearest integerMath.ceil(4.1)5
Math.round(x)Rounds to nearest integerMath.round(4.5)5
Math.trunc(x)Removes decimal part (truncates)Math.trunc(-4.7)-4

Key Takeaways

Math.floor(x) rounds a number down to the nearest integer.
It always rounds towards negative infinity, affecting negative numbers differently.
Use Math.trunc if you want to just remove decimals without rounding down.
Math.floor is useful for tasks like pagination, indexing, or any time you need whole numbers.
Remember that Math.floor(-4.1) returns -5, not -4.