Learn how to use JavaScript’s Math.floor() function to round numbers down to the nearest integer. Includes clear examples and real-world use cases for web development and random number generation.
In JavaScript, Math.floor() is a built-in function that rounds a number down to the nearest integer.
Math.floor(x)
x is the number you want to round down.Math.floor(4.7); // returns 4
Math.floor(4.1); // returns 4
Math.floor(-4.7); // returns -5
Math.floor() is often used with Math.random() to generate random integers:
// Random integer between 0 and 9
let randomInt = Math.floor(Math.random() * 10);