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

You can also try this code with Online Javascript Compiler
Run Code
Output:
4
Demonstrates rounding a number down to the nearest integer.
Rounding Down with Precision:
JavaScript
console.log(_.floor(4.006, 2));

You can also try this code with Online Javascript Compiler
Run Code
Output:
4.00
Shows rounding a number down to a specified decimal place.
Financial Calculations:
JavaScript
var amount = 1234.567;
var roundedAmount = _.floor(amount, 2); // Rounding down for financial amount
console.log(roundedAmount);

You can also try this code with Online Javascript Compiler
Run Code
Output:
1234.56
An example of using _.floor() in financial calculations to round down an amount.
Using in Array Operations:
JavaScript
var numbers = [1.8, 2.9, 3.5];
var roundedNumbers = numbers.map(num => _.floor(num));
console.log(roundedNumbers);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, 3]
Demonstrates rounding down each number in an array to the nearest integer.
Frequently Asked Questions
How does _.floor() differ from JavaScript's Math.floor()?
While both _.floor() and Math.floor() round numbers down, _.floor() provides the added functionality of specifying the precision to which the number should be rounded down.
Can _.floor() handle negative numbers?
Yes, _.floor() can round negative numbers down (further away from zero) to the specified precision.
Is _.floor() suitable for all numerical rounding needs?
_.floor() is ideal for cases where rounding down is explicitly required. For other types of rounding, other Lodash methods or native JavaScript functions might be more suitable.
Conclusion
Lodash's _.floor() method provides a flexible and precise way to round numbers down, 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.