JavaScript Math.floor(), ceil(), trunc() and round()
Quick answer
Four Math methods answer different rounding questions: floor toward negative infinity, ceil toward positive infinity, trunc toward zero, and round to nearest with ties toward positive infinity.
How it works
For negative nonintegers floor and trunc diverge. Math.round(-1.5) is -1, not -2. Several methods can return negative zero near zero. Each method converts its argument to Number and returns a Number; BigInt input is not accepted by Math conversion.
const x = -2.7;console.log(Math.floor(x), Math.ceil(x), Math.trunc(x), Math.round(x));Expected output in Node.js:
-3 -2 -2 -3Direction matters for negative fractions.
console.log(Math.round(2.5), Math.round(-2.5));console.log(Object.is(Math.round(-0.2), -0));Expected output in Node.js:
3 -2trueHalf ties go toward positive infinity; negative zero is preserved near zero.
Common mistakes
Do not use trunc in place of floor for negative bucket indices. Rounding a number to decimal places by scaling can introduce binary rounding errors.
Practice
Compare four rounding methods for -4.6, -4.5 and 4.5.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Math.floor(), ceil(), trunc() and round() — Knowledge Check
Apply the taught concept and predict the output.
Which method returns the greatest integer not greater than x?
What is Math.trunc(-3.9)?
Which rule describes Math.round half ties?
What is the exact console output in JavaScript Math.floor(), ceil(), trunc() and round() example 1?
const x = -2.7;console.log(Math.floor(x), Math.ceil(x), Math.trunc(x), Math.round(x));What is the exact console output in JavaScript Math.floor(), ceil(), trunc() and round() example 2?
console.log(Math.round(2.5), Math.round(-2.5));console.log(Object.is(Math.round(-0.2), -0));