Lodash _.floor vs Math.floor in JavaScript
While both Lodash’s _.floor and JavaScript’s native
Math.floor round numbers down to the nearest value, their
primary difference lies in precision handling. Native
Math.floor strictly rounds down to the nearest whole
integer and accepts only a single argument. In contrast, Lodash’s
_.floor includes an optional second parameter that allows
developers to specify decimal precision, supporting rounding down to
specific decimal places or powers of ten.
1. The Precision Parameter
The standard Math.floor() function accepts only one
argument:
Math.floor(4.567); // Returns 4To round down to two decimal places using vanilla JavaScript, you must manually multiply and divide:
Math.floor(4.567 * 100) / 100; // Returns 4.56Lodash simplifies this by accepting an optional
precision parameter:
_.floor(4.567, 2); // Returns 4.562. Negative Precision for Rounding Large Numbers
Lodash’s _.floor also supports negative precision,
allowing you to round down to tens, hundreds, thousands, or any other
power of ten:
_.floor(4120, -2); // Returns 4100
_.floor(4999, -3); // Returns 4000Achieving this natively requires similar mathematical scaling:
Math.floor(4120 / 100) * 100.
3. Floating-Point Arithmetic Accuracy
Manual multiplication and division with Math.floor can
occasionally cause floating-point rounding errors common to IEEE 754
arithmetic in JavaScript (such as 1.005 * 100 resulting in
100.49999999999999).
Lodash mitigates these issues internally by converting the number to exponential notation before applying the floor calculation, ensuring more reliable decimal truncation.
4. Performance and Dependencies
- Native
Math.floor: Built directly into the JavaScript engine. It executes significantly faster and requires zero external dependencies, making it the ideal choice for performance-critical tasks and standard integer rounding. - Lodash
_.floor: Requires importing a library or individual module. It introduces a small amount of function overhead, making it slightly slower than the native implementation, but it provides cleaner syntax and fewer floating-point pitfalls when decimal precision is needed.
When to Use Which
Use native Math.floor when you only need to truncate
floating-point numbers to integers. Choose Lodash’s _.floor
when working with decimal places, financial displays, or
negative-exponent rounding where convenience and floating-point safety
outweigh the negligible overhead of a utility library.