var someFloat = 0.123456789;
someFloat.toFixed(4);
someFloat.toPrecision(4);
(Math.round(someFloat*10000)/10000);
~~(someFloat * 10000) / 10000;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
toFixed(4) | |
toPrecision(4).toString() | |
(Math.round(*10000)/10000).toString() | |
Math.floor fast |
Test name | Executions per second |
---|---|
toFixed(4) | 8926744.0 Ops/sec |
toPrecision(4).toString() | 13439743.0 Ops/sec |
(Math.round(*10000)/10000).toString() | 138189568.0 Ops/sec |
Math.floor fast | 163922912.0 Ops/sec |
I'll break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is comparing four different methods to round or truncate a floating-point number:
toFixed()
toPrecision()
Math.round()
~~
)These methods are used to convert a decimal number to an integer, with varying levels of precision.
Options Compared
Here's what each method does:
toFixed(4)
: Rounds the number to 4 decimal places.toPrecision(4)
: Returns a string representation of the number with a maximum of 4 significant digits. This includes rounding or truncating the number to achieve this level of precision.Math.round()
: Rounds the number to the nearest integer.~~
): Uses a trick to round the number to the nearest integer without using Math.round()
.Pros and Cons
Here's a brief summary:
toFixed(4)
:toPrecision(4)
.toString()`:toFixed(4)
due to string conversion.Math.round()
:~~
):Library
The benchmark uses the ~~
operator, which is a bitwise NOT operator in JavaScript. This operator returns -1
if the number is negative and 0 otherwise. By multiplying the original number by -10000 and then adding 5000, we effectively round to the nearest integer using bitwise operations. The resulting value is then cast to an integer using ~~
.
Special JS Feature
The benchmark uses a feature called "bitwise operators" (e.g., ~~
), which are not typically used in everyday JavaScript development. This suggests that the test may be targeting specific use cases or hardware platforms where bitwise operations have performance advantages.
Other Alternatives
Some other methods for rounding floating-point numbers include:
Number.EPSILON
to determine the smallest positive value that can be added to 1 without exceeding it, and then using this value as a threshold for rounding.Math.ceil()
or Math.floor()
in combination with conditional statements to achieve the desired level of precision.decimal.js
or big.js
for high-precision arithmetic.These alternatives may offer better performance, accuracy, or readability, depending on the specific use case and requirements.