Math.round, Math.floor, and Math.ceil
What you'll learn: How to round numbers in three different ways depending on whether you need the nearest integer, always round down, or always round up.
The Three Rounding Methods
JavaScript provides three built-in methods for converting decimal numbers to integers, each with a distinct behavior:
Math.round() — Rounds to the nearest integer. If the decimal is 0.5 or higher, it rounds up; otherwise, it rounds down.
Math.round(4.3); // 4
Math.round(4.5); // 5
Math.round(4.7); // 5
Math.round(-4.5); // -4 (rounds toward zero on .5)
Math.floor() — Always rounds down to the nearest integer, like dropping down to the floor below you.
Math.floor(4.3); // 4
Math.floor(4.9); // 4 (still rounds down!)
Math.floor(-4.3); // -5 (down means more negative)
Math.ceil() — Always rounds up to the nearest integer, like rising to the ceiling above you.
Math.ceil(4.1); // 5
Math.ceil(4.9); // 5
Math.ceil(-4.9); // -4 (up means less negative)
When to Use Each
- Math.round(): General-purpose rounding, like displaying prices or ratings
- Math.floor(): When you need a guaranteed lower bound, like calculating full pages from total items
- Math.ceil(): When you need a guaranteed upper bound, like determining how many boxes you need to pack items
Analogy
Think of a staircase: Math.floor() always takes you to the step below, Math.ceil() always takes you to the step above, and Math.round() takes you to whichever step is closest.
Key Takeaway: Use Math.round() for nearest-integer rounding, Math.floor() to always round down, and Math.ceil() to always round up—each serves different scenarios where you need precise control over rounding direction.