JavaScript Reference ยท Math
Math.ceil() method
Reference for JavaScript Math.ceil(): round a number up to the next integer, behavior with negatives, -0, NaN and strings, plus paging and rounding to decimals.
Math.ceil() rounds a number up, toward positive infinity, and returns the smallest integer that is greater than or equal to it. Math.ceil(4.1) is 5, and Math.ceil(4) is 4. The name is short for "ceiling".
Rounding up is the right choice whenever you need "enough": how many pages hold 53 items at 10 per page, how many boxes you need, or how many whole seconds cover a duration.
Math.ceil(4.1); // 5 Math.ceil(-4.9); // -4
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.ceil(x)
| Name | Description |
|---|---|
x |
A number. Other values are converted to a number first. |
Return value: the smallest integer greater than or equal to x. The result is NaN for NaN or non-numeric input, and Infinity or -Infinity stay as they are. Values between -1 and 0 give -0.
Exceptions: a TypeError for a BigInt or a Symbol.
Usage notes
- Negative numbers round toward zero. "Up" means toward positive infinity, so
Math.ceil(-4.9)is-4, not-5. UseMath.floor()for the opposite direction, andMath.trunc()to always move toward zero. -0is possible.Math.ceil(-0.2)returns-0. Consoles may print it as-0, but it equals0with===; onlyObject.is()or1 / xtells them apart in code.- Floating-point noise can surprise you. A result that should be exactly
3may be3.0000000000000004, andMath.ceilthen returns4. For division of integers, prefer integer arithmetic where you can. - Integers are unchanged, and very large numbers (beyond about
2^52) are already whole. - Rounding to decimals needs scaling by a power of ten, as in the second example. Rounding after multiplying can hit floating-point error again, so use it for display, not for money.
- Common uses: pagination, grid rows, chunk counts, timeouts in whole seconds.
- Strings are coerced:
Math.ceil("3.2")is4. Validate data first if you do not want that.
Browser support
Math.ceil() is available in every browser and JavaScript runtime.
Related
Math.floor(),Math.round(),Math.trunc(),toFixed()- Lessons: Math, Numbers