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
Selected Reading
Return the nearest greater integer of the decimal number it is being called on in JavaScript
The Math.ceil() function returns the smallest integer greater than or equal to a given number. This means it "rounds up" to the nearest integer.
Syntax
Math.ceil(x)
Parameters
x: A number to round up to the nearest integer.
Return Value
Returns the smallest integer greater than or equal to the given number. If the input is not a number, returns NaN.
Example: Basic Usage
console.log(Math.ceil(4.3)); // 5 console.log(Math.ceil(4.8)); // 5 console.log(Math.ceil(5.0)); // 5 (already integer) console.log(Math.ceil(-2.3)); // -2 console.log(Math.ceil(-2.8)); // -2
5 5 5 -2 -2
Example: Custom Implementation
Here's how you could implement a custom ceiling function:
function customCeil(num) {
if (typeof num !== 'number') {
return NaN;
}
// If already an integer, return as is
if (num % 1 === 0) {
return num;
}
// For positive numbers, add 1 to the integer part
if (num > 0) {
const [main] = String(num).split('.');
return +main + 1;
}
// For negative numbers, just remove decimal part
return Math.trunc(num);
}
console.log(customCeil(234.56)); // 235
console.log(customCeil(-4.3)); // -4
console.log(customCeil(7.0)); // 7
console.log(customCeil("abc")); // NaN
235 -4 7 NaN
Key Points
-
Math.ceil()always rounds towards positive infinity - For positive numbers: rounds up to next integer
- For negative numbers: rounds towards zero (appears to round "up")
- Integer inputs return unchanged
- Non-numeric inputs return
NaN
Comparison with Other Rounding Methods
| Method | 4.3 | 4.8 | -2.3 | -2.8 |
|---|---|---|---|---|
Math.ceil() |
5 | 5 | -2 | -2 |
Math.floor() |
4 | 4 | -3 | -3 |
Math.round() |
4 | 5 | -2 | -3 |
Conclusion
Math.ceil() is the standard method to round numbers up to the nearest integer. It handles both positive and negative numbers consistently by always rounding towards positive infinity.
Advertisements
