function round2(num, places) {
return +(Math.round(num + "e+" + places) + "e-" + places);
}
function round3(num, places) {
if (places === 2) {
return Math.round( Math.round( num * 1000 ) / 10 ) / 100
} else {
const multiplier = Math.pow(10, places)
return Math.round(num * multiplier) / multiplier
}
}
function round4(num, places) {
+(num.toLocaleString(
'en',
{ maximumFractionDigits: places, useGrouping: false }
))
}
Math.round(12.345 * 100) / 100
round2(12.345, 2)
round3(12.345, 2)
round4(12.345, 2)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Simple rounding | |
Rounding with epsilon and string conversion | |
Rounding with "if" statement | |
Rounding by toLocaleString |
Test name | Executions per second |
---|---|
Simple rounding | 10991604.0 Ops/sec |
Rounding with epsilon and string conversion | 184544.5 Ops/sec |
Rounding with "if" statement | 5203109.5 Ops/sec |
Rounding by toLocaleString | 954.4 Ops/sec |
Let's dive into the provided benchmark.
Benchmark Definition
The benchmark measures the performance of different rounding methods in JavaScript. The Script Preparation Code
section defines three custom rounding functions: round2
, round3
, and round4
. These functions are used to round numbers with a specified number of decimal places.
Options Compared
The benchmark compares the performance of these three custom rounding functions (round2
, round3
, and round4
) against each other. The options being compared are:
Math.round
function to round a number, adding and subtracting a small value (epsilon) to handle non-integer values.toLocaleString
method to format a number as a string, which effectively rounds it.Pros and Cons of Each Approach
Math.round
and string manipulation.Math.round
or toLocaleString
.toLocaleString
.Library and Purpose
The toLocaleString
method is a built-in JavaScript method that formats a number as a string according to the locale's conventions. In this benchmark, it is used to round numbers by formatting them as strings.
Special JS Feature or Syntax
None of the provided benchmark code uses any special JavaScript features or syntax beyond what is standard in JavaScript (e.g., functions, loops, conditional statements). However, the use of Math.round
and toLocaleString
methods implies that the benchmark is running on a platform that supports these built-in methods.
Alternatives
If you were to rewrite this benchmark using alternative approaches, some options might include:
decimal.js
) instead of implementing custom rounding functions.Keep in mind that the choice of alternative approaches would depend on the specific requirements and goals of the benchmark.