Explain Codes LogoExplain Codes Logo

How to format numbers as currency strings

javascript
number-formatting
intl-numberformat
currency-formatting
Anton ShumikhinbyAnton Shumikhin·Aug 27, 2024
TLDR

Here's a fast and efficient way to format a number as a currency using Intl.NumberFormat:

const formatCurrency = (num) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(num); console.log(formatCurrency(123456.789)); // Outputs: "$123,456.79"

You just need to replace 'en-US' and 'USD' with your preferred locale and currency code.

The nitty-gritty of Intl.NumberFormat

Intl.NumberFormat is a real deal in JavaScript for language-sensitive number formatting. When you align it with {style: 'currency', currency: 'USD'}, you transform sober numbers into currency protagonists. So, let's gear up to unravel its potential.

Dynamically setting locale

Catering to user's preferences is vital. You can format number currencies using the user's locale by setting the locale to undefined or using navigator.language:

const userLocale = navigator.language; // snagging user's locale const formatCurrency = (num) => new Intl.NumberFormat(userLocale, { style: 'currency', currency: 'EUR' // Suited for Euro }).format(num); console.log(formatCurrency(123456.789)); // Outputs currency based on user's locale

Tailoring decimal digits

You can get granular control over the decimal points displayed with the utilitarian minimumFractionDigits and maximumFractionDigits options:

const formatCurrency = (num) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(num); console.log(formatCurrency(123456.789)); // Outputs: "$123,457"

Mastering efficiency in currency formatting

When multiple numbers are to be formatted, create a single instance of Intl.NumberFormat and reuse it. Remember, efficiency is key:

const currencyFormatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }); const prices = [9.99, 49.99, 299.99]; console.log(prices.map(currencyFormatter.format)); // Reduces computational load

Tackling legacies and browser compatibility

Intl is supported by most modern browsers, yet for legacy browsers, verify that Intl is on deck. You might need polyfills. For Node.js versions without full-icu, consider using the full-icu package to enable complete internationalization support.

Beyond basic formatting - going the extra mile

Formulating your own formatting strategy

The standard formatting might not cover every scenario. You can construct a custom formatMoney function to personalize the currency representation. This function will handle negative values and integrate thousand separators with confidence:

const formatMoney = (amount) => { let formatted = amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'); if (amount < 0) formatted = `-${formatted}`; // handles negative values with grace, just like your bank balance :D return `$${formatted}`; };

Handling currencies and locales elegantly

Currencies abound in variety. Visit "www.iban.com/currency-codes" to find the code reflecting your currency of interest.

// Example: Formatting for Japanese Yen const formatCurrency = (num) => new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' // JPY for Yen }).format(num); console.log(formatCurrency(123456.789)); // Generates ¥123,457

Open MDN Web Docs on Intl.NumberFormat for a comprehensive list of locales and options.

Live demonstrations - a walk in the park

Just reading about functions might not be enough. Interactive examples, like on JSFiddle or CodePen, facilitate testing of functions real-time.

Mandatory sign display

It's common to grapple with percentages while formatting currencies. The signDisplay option handles signs for [0,positive,negative] cases with aplomb:

const percentFormat = new Intl.NumberFormat('en-US', { style: 'percent', signDisplay: 'always' }).format; console.log(percentFormat(0.123)); // "+12%" console.log(percentFormat(-0.123)); // "-12%" - A loss best served with a sign ;-)

Formatting in real-time

Our formatMoney function can pair with event listeners for currency formatting over user inputs at runtime:

document.getElementById('currency-input').addEventListener('input', (event) => { event.target.value = formatMoney(parseFloat(event.target.value)); // Auto-magically formats user input });

Error proofing custom functions

Safeguard custom functions against unexpected crashes by using typeof to check parameter types.