Math.floor(x) rounds a number toward negative infinity and returns the greatest integer less than or equal to the input. With negative decimals, the result becomes more negative.
console.log(Math.floor(7.9)); // 7
console.log(Math.floor(-7.1)); // -8Math.floor(number)console.log(Math.floor(11.257)); // 11
console.log(Math.floor(1.56)); // 1
console.log(Math.floor(4)); // 4console.log(Math.floor(-3.564)); // -4
console.log(Math.floor(-7.164)); // -8console.log(Math.floor()); // NaN
console.log(Math.floor("abc")); // NaNSee NaN for invalid numerical results.
const value = -5.42;
console.log(Math.floor(value)); // -6
console.log(Math.round(value)); // -5
console.log(Math.ceil(value)); // -5
console.log(Math.trunc(value)); // -5Math.trunc() removes the fractional part toward zero, so it differs from Math.floor() for negative values. See Math.ceil(), Math.round(), and toFixed().
const die = Math.floor(Math.random() * 6) + 1;
console.log(die); // 1 through 6Math.floor(Infinity) remains Infinity, while invalid numeric input produces NaN. A negative zero can also be preserved in some cases. For form input, convert and validate explicitly instead of depending on implicit coercion.
console.log(Math.floor(Infinity)); // Infinity
console.log(Math.floor("8.9")); // 8Math.floor() does not merely remove decimal digits. For negative values it moves toward negative infinity, so Math.floor(-3.2) is -4, while Math.trunc(-3.2) is -3. Choose the operation that matches the rule you actually need.
const seconds = 367;
const minutes = Math.floor(seconds / 60);
console.log(minutes); // 6 complete minutes
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Makwana Parvez | 11-02-2019 |
| very good and explaination of example is very nice | |