How to format a currency with trailing ISO code in Javascript?

Viewed 322

Given a value of 1000.5, I want to format it as 1,000.50 USD (where the trailing currency code is the most relevant part). Performance is also important, as the formatting will be issued for millions of values. Hence, regex is discouraged.

Can you accomplish this using Intl.NumberFormat or some other standardized JavaScript number formatting API?

Example:

const formatter = Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', currencyDisplay: 'code' })
formatter.format(1000.5)

Actual:

USD 1,000.50

Expected:

1,000.50 USD

1 Answers

Here's a simple function that formats with a trailing ISO code.

   function FormatWithTrailingISO(currency, type,num) {
    const formatter = Intl.NumberFormat(type, {
      style: "currency",
      currency: currency,
      currencyDisplay: "code",
    });
    return formatter.format(num).replace(currency, "") + " " + currency;
   }

Usage:

console.log(FormatWithTrailingISO("USD", "en-US", 1000.5).trim());
Related