<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
var someFloat = 0.123456789;
someFloat.toFixed(4);
someFloat.toPrecision(4);
(Math.round(someFloat*10000)/10000);
~~(someFloat * 10000) / 10000;
Math.trunc(someFloat * 10000) / 10000;
numeral(someFloat).format('0.0000');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
toFixed(4) someFloat.toFixed(4); someFloat.t | |
toPrecision(4).toString() | |
(Math.round(*10000)/10000).toString() | |
Math.floor fast | |
Math.trunc | |
numeraljs |
Test name | Executions per second |
---|---|
toFixed(4) someFloat.toFixed(4); someFloat.t | 5881193.0 Ops/sec |
toPrecision(4).toString() | 4739471.5 Ops/sec |
(Math.round(*10000)/10000).toString() | 4675021.5 Ops/sec |
Math.floor fast | 12324935.0 Ops/sec |
Math.trunc | 4709398.0 Ops/sec |
numeraljs | 483498.4 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance of different methods for rounding and formatting decimal numbers in JavaScript. The test cases compare the execution time of various functions, including toFixed
, toPrecision
, Math.round
, Math.floor fast
(a shorthand for ~~(someFloat * 10000) / 10000
), Math.trunc
, and a library-based function using Numeral.js.
Methods Compared
toFixed(4)
: Rounds the number to 4 decimal places.toPrecision(4).toString()
: Formats the number as a string with 4 significant digits.toFixed
, can handle different precision requirements.(Math.round(someFloat * 10000) / 10000).toString()
: Rounds the number using Math.round
and then divides by 10000.Math.floor fast
(shorthand for ~~(someFloat * 10000) / 10000
): Rounds the number using the bitwise NOT operator (~
) to truncate it.Math.trunc
: Rounds the number to the nearest integer.numeral(someFloat).format('0.0000')
(using Numeral.js): Formats the number as a string with 6 decimal places using the Numeral.js library.Library Used
The numeraljs
library is used in one of the test cases to format the number as a string with 6 decimal places. Numeral.js provides a convenient and flexible way to work with numbers, but it does require an external library.
Special JavaScript Feature/Syntax
None mentioned in this benchmark.
Other Alternatives
Other alternatives for rounding and formatting decimal numbers in JavaScript include:
Number.EPSILON
constant to determine the smallest representable floating-point value.~~
or << 1
.Benchmark Results
The benchmark results show that the execution times vary depending on the method used. The fastest methods are Math.floor fast
and Math.trunc
, while toFixed(4)
and toPrecision(4).toString()
are slower due to the extra conversions required. The Numeral.js implementation is also slower than the native JavaScript implementations.
Note that these results may vary depending on the specific browser, platform, and hardware used for running the benchmark.