var someFloat = 0.1256;
someFloat.toFixed(2);
Math.round(someFloat * 100) / 100;
((someFloat * 100) | 0 ) / 100;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
someFloat.toFixed(2); | |
Math.round(someFloat * 100) / 100; | |
((someFloat * 100) | 0 ) / 100; |
Test name | Executions per second |
---|---|
someFloat.toFixed(2); | 4289698.5 Ops/sec |
Math.round(someFloat * 100) / 100; | 3824472.5 Ops/sec |
((someFloat * 100) | 0 ) / 100; | 11622679.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, compared, and their pros and cons.
Benchmark Overview
The test compares the performance of three methods to round or format a floating-point number:
toFixed(2)
: Formats a float as a string with the specified number of digits after the decimal point.Math.round(someFloat * 100) / 100
: Multiplies the float by 100, rounds to the nearest integer using Math.round
, and then divides by 100 to get the original value back.(someFloat * 100 | 0) / 100
: Uses bitwise OR (|) with 0 to effectively truncate the float, and then divides by 100.Pros and Cons of Each Approach
toFixed(2)
:Math.round(someFloat * 100) / 100
:(someFloat * 100 | 0) / 100
:Library Used
In this benchmark, the Math.round()
function is used from the built-in JavaScript Math library. The purpose of Math.round()
is to round a number to the nearest integer, which is then divided by 100 to get back to the original value.
Special JS Feature/Syntax
None mentioned in the provided code.
Alternatives
Some alternative approaches could be:
Number.EPSILON
and comparing the difference between two values to determine if they are close enough to round.decimal.js
for precise decimal arithmetic.However, these alternatives might not provide significant performance benefits over the built-in Math.round()
function and may require more code and expertise.
Benchmark Preparation Code
The script preparation code is:
var someFloat = 0.1256;
This sets a sample float value for testing.
Individual Test Cases
Each test case consists of a single benchmark definition:
someFloat.toFixed(2);
: Formats the float as a string with two decimal places.Math.round(someFloat * 100) / 100;
: Multiplies, rounds, and divides to get back to the original value.(someFloat * 100 | 0) / 100;
: Truncates and divides.The test result is a list of raw UA strings (browser versions), browser names, device platforms, operating systems, executions per second, and test names for each case.