JavaScript Math.floor()

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));  // -8

Math.floor() syntax Top ↑

Math.floor(number)

Positive numbers Top ↑

console.log(Math.floor(11.257)); // 11
console.log(Math.floor(1.56));   // 1
console.log(Math.floor(4));      // 4

Negative numbers Top ↑

console.log(Math.floor(-3.564)); // -4
console.log(Math.floor(-7.164)); // -8

Invalid and missing values Top ↑

console.log(Math.floor());       // NaN
console.log(Math.floor("abc"));  // NaN

See NaN for invalid numerical results.

Math.floor(), Math.round(), Math.ceil() and Math.trunc() Top ↑

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)); // -5

Math.trunc() removes the fractional part toward zero, so it differs from Math.floor() for negative values. See Math.ceil(), Math.round(), and toFixed().

Using Math.floor() for random integers Top ↑

const die = Math.floor(Math.random() * 6) + 1;
console.log(die); // 1 through 6

Infinity, negative zero and coercion Top ↑

Math.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")); // 8

Common Math.floor() mistakes Top ↑

Math.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.

Using Math.floor() for indexes and buckets Top ↑

const seconds = 367;
const minutes = Math.floor(seconds / 60);
console.log(minutes); // 6 complete minutes



Subscribe to our YouTube Channel here



plus2net.com







Makwana Parvez

11-02-2019

very good and explaination of example is very nice



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer