new Intl.NumberFormat('en-US', {
style: 'decimal',
useGrouping: true,
minimumFractionDigits: 0,
maximumFractionDigits: 3,
}).format('100000.234')
const value = '100000.234';
function decimalFormat(value) {
// fix for rounding issues, see Mozilla docs on method toFixed()
const normalizedValue = value * 10 ** 3;
const formattedValue = normalizedValue.toFixed(0);
return +formattedValue / 10 ** 3;
}
function formatThousandsSeparator(value) {
// TODO: consider replacing this later with Intl.NumberFormat
const parts = value.toString().split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return parts.join('.');
}
decimalFormat(formatThousandsSeparator(value))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Intl | |
String |
Test name | Executions per second |
---|---|
Intl | 29760.8 Ops/sec |
String | 2020179.9 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark is defined as a comparison between two approaches to format numbers:
Intl.NumberFormatter
(the "Intl" test case)What are we comparing?
We're comparing the performance of these two approaches in formatting a number with decimal places.
Options being compared:
Pros and Cons of each approach:
Other considerations:
decimalFormat
function in the "String" test case. This is likely used to demonstrate the required formatting behavior.Intl.NumberFormatter
instance in the "Intl" test case has some configuration options set (e.g., style='decimal'
, useGrouping=true
). These settings might affect the performance and accuracy of the formatter.Library:
The Intl.NumberFormatter
library is a part of the JavaScript Standard Library, introduced in ECMAScript 2015 (ES6). It provides a standardized way to format numbers according to cultural and linguistic conventions.
Special JS feature or syntax:
There are no special JavaScript features or syntaxes used in this benchmark. The focus is on comparing two approaches for formatting numbers.
Now that we've broken down the benchmark, let's talk about alternatives:
In summary, this benchmark compares the performance of two approaches for formatting numbers: using Intl.NumberFormatter
and string manipulation. It highlights the pros and cons of each approach and provides insights into the behavior of these methods in different scenarios.