JavaScript Reference ยท Math
Math.floor() method
Reference for JavaScript Math.floor(): round a number down to the previous integer, negative numbers, floor division, random integers and common pitfalls.
Math.floor() rounds a number down, toward negative infinity, and returns the largest integer that is less than or equal to it. Math.floor(4.9) is 4. For positive numbers it simply drops the decimals, but for negative numbers it moves further from zero: Math.floor(-4.1) is -5.
It is the building block for integer division, for turning a random fraction into a random integer, and for snapping values to a grid.
Math.floor(4.9); // 4 Math.floor(-4.1); // -5
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Math.floor(x)
| Name | Description |
|---|---|
x |
A number. Other values are converted to a number first. |
Return value: the largest integer less than or equal to x. NaN stays NaN, Infinity and -Infinity stay as they are, and -0 stays -0.
Exceptions: a TypeError for a BigInt or a Symbol.
Usage notes
- Negative numbers go away from zero.
Math.floor(-2.7)is-3. If you want to cut off the decimals toward zero, useMath.trunc(). - Integer division:
Math.floor(a / b)works for positive operands. For negative operands the result follows "round down", which differs from languages that truncate toward zero. - Floor modulo: the
%operator keeps the sign of the left side (-7 % 3is-1). For a result that is always non-negative, use((a % n) + n) % n. - Random integers:
Math.floor(Math.random() * n)gives0ton - 1. Never useMath.round()for this, because it makes the end values half as likely. - Floating-point noise:
0.29 * 100is28.999999999999996, just below the whole number you expect, soMath.floorreturns28. Be careful with decimal-looking arithmetic (see floating-point numbers). - Bit tricks like
x | 0also remove decimals but wrap numbers above 32 bits and treat negatives as truncation.Math.floor()is clearer and safe for any size. - Strings are coerced:
Math.floor("7.8")is7.
Browser support
Math.floor() is available in every browser and JavaScript runtime.
Related
Math.ceil(),Math.round(),Math.trunc(),Math.random()- Lessons: Math, Numbers