Math.trunc(13.37123123 * 1_000_000) / 1_000_000
Math.trunc(13.67123123 * 1_000_000) / 1_000_000
Math.round(13.37123123, 6)
Math.round(13.67123123, 6)
Math.floor(13.37123123, 6)
Math.floor(13.67123123, 6)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
trunc | |
round | |
floor |
Test name | Executions per second |
---|---|
trunc | 241060112.0 Ops/sec |
round | 258677504.0 Ops/sec |
floor | 243322448.0 Ops/sec |
The benchmark titled "round vs trunc vs floor (2)" is designed to measure and compare the performance of three different JavaScript functions that are used to manipulate numerical values: Math.round()
, Math.trunc()
, and Math.floor()
. Each of these functions has its specific behavior when handling decimal numbers, which influences both their performance and output.
Math.round():
Math.round(13.37123123, 6)
rounds the number to six decimal places. However, in JavaScript, the second parameter is ignored, lending a possible performance aspect to consider.Math.trunc():
Math.trunc(13.37123123 * 1_000_000) / 1_000_000
shifts the decimal six places, truncates, and shifts back.Math.floor():
Math.floor(13.37123123, 6)
behaves similarly to round, but given JavaScript's handling of additional parameters, the second parameter is ignored.The benchmarking results show the number of executions per second for each of the three methods in a specific browser context:
Math.round():
Math.trunc():
Math.floor():
Alternatives: If needing to round numbers to specific decimal places, one could use custom functions or libraries that provide more granularity than the basic Math functions. Libraries such as Lodash can provide additional options for manipulating numbers more effectively than the basic Math API.
Library Use: No external libraries are needed for these basic arithmetic operations, as they are provided natively by JavaScript. However, when more complex numerical manipulation is necessary, developers might consider using libraries.
This benchmark provides insight into how performance varies between different numerical manipulation techniques in JavaScript. Based on execution speed, Math.round()
performs the best among the options tested, with Math.floor()
and Math.trunc()
following closely. Understanding the implications of each method is essential for selecting the right approach depending on the specific scenario in software development.