<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var x = Math.random() * 100;
for (var i = 0; i < 1000; i++) {
_.round(x, 2);
}
for (var i = 0; i < 1000; i++) {
Number(x.toFixed(2));
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Round floating number using lodash round function | |
Round floating number using toFixed() |
Test name | Executions per second |
---|---|
Round floating number using lodash round function | 4348.5 Ops/sec |
Round floating number using toFixed() | 12876.0 Ops/sec |
Let's break down the benchmark and its results.
Benchmark Overview
The benchmark compares two approaches to rounding numbers in JavaScript: Lodash's round
function and the native toFixed
method.
Lodash's Round Function
Lodash is a popular utility library for JavaScript. Its round
function takes two arguments: the number to be rounded, and the precision (number of decimal places). The function returns the rounded value as a string.
In this benchmark, Lodash's round
function is used with a precision of 2.
Native toFixed Method
The native toFixed
method in JavaScript rounds a number to a specified number of decimal places. It takes two arguments: the number to be rounded, and the number of decimal places.
In this benchmark, the native toFixed
method is used with a precision of 2.
Pros and Cons
Both approaches have their pros and cons:
round
function.Other Considerations
x
) to avoid JavaScript engine optimizations. This ensures that the results are consistent across different browsers and engines.use strict
mode is not specified in the benchmark, which means it will default to non-strict mode. If you want to test with use strict
, you'll need to add it explicitly to your script.Latest Benchmark Results
The latest benchmark results show that:
toFixed
method, executing 1034.35 times more than Lodash's round
function.Other Alternatives
If you're interested in exploring other rounding methods or libraries, here are a few alternatives:
Number.EPSILON
constant to calculate the smallest representable value of a number.