const formatNumberToFloat = new Intl.NumberFormat('ru-RU', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2,
})
const formatNumberToFloat = new Intl.NumberFormat('ru-RU', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2,
})
var a = formatNumberToFloat.format("10000.999999");
var a = (Math.round( "10000.999999" * 100 + Number.EPSILON ) / 100).toFixed(2);
var b = a.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Intl.NumberFormat | |
toLocalString |
Test name | Executions per second |
---|---|
Intl.NumberFormat | 36439.8 Ops/sec |
toLocalString | 3229272.0 Ops/sec |
Let's break down the benchmark and its components.
Overview
The benchmark compares two approaches to formatting numbers: using the Intl.NumberFormat
API and regular expressions (RegExp). The goal is to determine which approach is faster for this specific use case.
** Intl.NumberFormat API**
The Intl.NumberFormat
API is a built-in JavaScript API that provides support for formatting numbers according to the rules of different cultures. In this benchmark, we're using it to format a Russian decimal number with two fractional digits.
Script Preparation Code
The script preparation code creates an instance of Intl.NumberFormat
with specific settings:
const formatNumberToFloat = new Intl.NumberFormat('ru-RU', {
style: 'decimal',
maximumFractionDigits: 2,
minimumFractionDigits: 2,
});
This code sets the formatting style to decimal, and limits the number of fractional digits to 2.
Test Case
The test case consists of two parts:
a
using the formatNumberToFloat
instance:var a = formatNumberToFloat.format("10000.999999");
This code formats the string "10000.999999" according to the Russian decimal rules, resulting in a formatted number.
a
using regular expressions:var b = (Math.round("10000.999999" * 100 + Number.EPSILON) / 100).toFixed(2);
var c = b.replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, '$1 ');
This code uses regular expressions to extract every third digit from the number and append a space after each one.
Pros and Cons
Using Intl.NumberFormat
has several advantages:
However, using Intl.NumberFormat
also has some limitations:
On the other hand, regular expressions (RegExp) have the following advantages:
However, using RegExp also has some disadvantages:
Intl.NumberFormat
.Other Considerations
Another consideration is that this benchmark only measures the execution time of formatting a single number. In real-world scenarios, you may need to format multiple numbers, which could impact the overall performance.
Additionally, if you're using Intl.NumberFormat
, make sure to handle errors and exceptions properly, as it can throw errors for invalid input or unsupported locales.
Alternatives
If you don't want to use Intl.NumberFormat
, alternative approaches include:
However, these alternatives may have their own trade-offs in terms of performance, accuracy, and maintainability.