Test name | Executions per second |
---|---|
Intl | 29760.8 Ops/sec |
String | 2020179.9 Ops/sec |
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))