Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Display the result difference while using ceil() in JavaScript?
The Math.ceil() function rounds a number UP to the nearest integer. While division might give decimal results, Math.ceil() ensures you get the next whole number.
How Math.ceil() Works
If your value is 4.5, 4.3, or even 4.1, Math.ceil() will return 5. It always rounds UP, unlike regular rounding.
Example: Division Without ceil()
Let's see normal division first:
var result1 = 98;
var result2 = 5;
console.log("The actual result is=" + result1 / result2);
The actual result is=19.6
Example: Division With ceil()
Now let's apply Math.ceil() to round up:
var result1 = 98;
var result2 = 5;
console.log("The actual result is=" + result1 / result2);
var output = Math.ceil(result1 / result2);
console.log("The ceil result is=" + output);
The actual result is=19.6 The ceil result is=20
More Examples
Here are additional examples showing how Math.ceil() always rounds up:
console.log("Math.ceil(4.1) =", Math.ceil(4.1));
console.log("Math.ceil(4.9) =", Math.ceil(4.9));
console.log("Math.ceil(5.0) =", Math.ceil(5.0));
console.log("Math.ceil(-4.1) =", Math.ceil(-4.1));
Math.ceil(4.1) = 5 Math.ceil(4.9) = 5 Math.ceil(5.0) = 5 Math.ceil(-4.1) = -4
Comparison: ceil vs floor vs round
| Input | Math.ceil() | Math.floor() | Math.round() |
|---|---|---|---|
| 4.1 | 5 | 4 | 4 |
| 4.6 | 5 | 4 | 5 |
| -4.1 | -4 | -5 | -4 |
Common Use Cases
Math.ceil() is useful when you need to ensure sufficient resources, like calculating the minimum number of pages needed or determining container capacity.
Conclusion
Math.ceil() always rounds UP to the nearest integer, making it perfect for scenarios where you need the next whole number rather than truncating decimals.
