Currency Formatting Test

Benchmark created on


Setup

const formatCurrency1 = (number, config) => {
    const { style } = config ?? {};
    const defaultStyle = style ?? 'currency';
    const isFormattedAsCurrency = defaultStyle === 'currency';

    return new Intl.NumberFormat(config.locale ?? config.appDefaultCurrencyLocale, {
        style: defaultStyle,
        currency: config.currency ?? isFormattedAsCurrency ? config.appDefaultCurrency : undefined,
        currencyDisplay: config.currencyDisplay ?? isFormattedAsCurrency ? 'narrowSymbol' : undefined,
        ...config,
    }).format(number);
};

const formatCurrency2 = (value, config) => {
	const fixedValue = Number(value).toFixed(2);
    const integerLength = fixedValue.length - 3;
    const offset = integerLength % 3;
    const hasTrailingZeros = fixedValue[fixedValue.length - 1] === '0' && fixedValue[fixedValue.length - 2] === '0';
    let index = 0;
    let formattedValue = '';
    for (const char of fixedValue) {
        if (index < integerLength) {
            if (index > 0 && (index - offset) % 3 === 0) {
                formattedValue += '’';
            }
            formattedValue += char;
        } else {
            if (
                !(
                    (config.trailingZeroDisplay === 'stripIfInteger' && hasTrailingZeros) ||
                    (config.cutFractionAfterIntegerDigits && integerLength >= config.cutFractionAfterIntegerDigits)
                )
            ) {
                formattedValue += char;
            }
        }
        index += 1;
    }

    if (config.currency) {
        return `${config.currency} ${formattedValue}`;
    }

    return formattedValue;
};

Test runner

Ready to run.

Testing in
TestOps/sec
formatCurrency1
formatCurrency1(12345.654, {
        appDefaultCurrency: 'CHF',
        appDefaultCurrencyLocale: 'de-CH',
        minimumFractionDigits: 0,
        maximumFractionDigits: 2,
});
ready
formatCurrency2
formatCurrency2(12345.654, {
	cutFractionAfterIntegerDigits: 5,
	trailingZeroDisplay: 'stripIfInteger'
});
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.