JavaScriptNumbers and Math
Math. floor()
Rounds a number down, to the nearest smaller integer.
- Returns
- The largest integer less than or equal to
x.
Example
#JavaScript
console.log(Math.floor(4.9))
console.log(Math.floor(-2.3))
const seconds = 185
console.log(`${Math.floor(seconds / 60)} min ${seconds % 60} s`)Console
4
-3
3 min 5 s
Definition and usage
#The Math.floor() function returns the largest integer that isn’t greater than the given number. For positive numbers, it simply cuts off the fractional part.
For negative numbers it rounds further from zero: Math.floor(-2.3) gives -3. If you just want to cut off the fraction regardless of sign, use Math.trunc().
It’s very often combined with Math.random() when picking random integers, and with division when counting full units, for example full minutes from seconds.
Syntax
#Syntax
Math.floor(x)Parameters
#x
number
The number to round down.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- With negative numbers,
floorandtruncgive different results. Choose deliberately. - A random integer from 0 to n-1:
Math.floor(Math.random() * n).
Related entries
#Spotted a mistake or missing an example? Write to us.