Syntax, Parameter and Return Value
Syntax:
_.ceil(number, [precision=0])
Parameters:
-
number (Number): The number to round up.
- [precision=0] (Number): The precision to round up to (number of decimal places).
Return Value:
(Number) - Returns the rounded up number.
Examples
Rounding Up to Nearest Integer:
JavaScript
var _ = require('lodash');
console.log(_.ceil(4.006));

You can also try this code with Online Javascript Compiler
Run Code
Output:
5
Demonstrates rounding a number up to the nearest integer.
Rounding Up with Precision:
JavaScript
console.log(_.ceil(6.004, 2));

You can also try this code with Online Javascript Compiler
Run Code
Output:
6.01
Shows rounding a number up to a specified decimal place.
Financial Calculations:
JavaScript
var price = 39.952;
var finalPrice = _.ceil(price, 2); // Rounding up for pricing
console.log(finalPrice);

You can also try this code with Online Javascript Compiler
Run Code
Output:
39.96
An example of using _.ceil() in financial calculations to round prices.
Using in Array Operations:
JavaScript
var numbers = [1.5, 2.1, 3.7];
var roundedNumbers = numbers.map(num => _.ceil(num));
console.log(roundedNumbers);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[2, 3, 4]
Demonstrates rounding up each number in an array to the nearest integer.
Frequently Asked Questions
How does _.ceil() differ from JavaScript's Math.ceil()?
While both round numbers up, _.ceil() provides additional functionality by allowing you to specify the precision (decimal places), unlike Math.ceil() which only rounds to the nearest integer.
Can _.ceil() handle negative numbers?
Yes, _.ceil() can round negative numbers up (towards zero) to the specified precision.
Is _.ceil() suitable for all numerical rounding needs?
_.ceil() is ideal for cases where rounding up is explicitly required. For other types of rounding (like rounding down or to the nearest integer), other Lodash methods or native JavaScript functions might be more suitable.
Conclusion
Lodash's _.ceil() method offers a flexible and precise way to round numbers up, accommodating a variety of scenarios where control over rounding precision is important. It's a valuable tool in financial calculations, data processing, and any situation where specific rounding behavior is required.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.