Intl.NumberFormat is the built-in JavaScript API for formatting numbers according to locale rules, currency codes, and display styles. Instead of hardcoding currency symbols or decimal separators, you pass a BCP 47 locale (or undefined for the runtime’s default locale) and { style: "currency", currency: "ISO_CODE" }.
1. Basic Currency Formatting with Intl.NumberFormat
Always provide an explicit 3-letter ISO 4217 currency code when style: "currency" is set. Reusing a formatter instance is also clean and efficient when formatting many amounts:
function formatCurrency(amount, currency = "USD", locale = undefined) {
return new Intl.NumberFormat(locale, {
style: "currency",
currency
}).format(amount);
}
console.log(formatCurrency(1250.5, "USD", "en-US")); // "$1,250.50"
console.log(formatCurrency(1250.5, "EUR", "de-DE")); // "1.250,50 €"
console.log(formatCurrency(150000, "PKR", "en-PK")); // "PKR 150,000.00" (locale/ICU dependent)
2. Controlling Currency Display, Decimals, and Rounding
You can customize how currency codes or symbols appear, adjust fraction digits, and control rounding behavior:
const compactUsd = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
notation: "compact",
maximumFractionDigits: 1
});
const codeDisplay = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
currencyDisplay: "code"
});
const wholeUnits = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0
});
console.log(compactUsd.format(2450000)); // "$2.5M"
console.log(codeDisplay.format(49.99)); // "USD 49.99"
console.log(wholeUnits.format(49.99)); // "$50"
3. Common Traps to Avoid
- Omitting
currencywhenstyle: "currency"is set: JavaScript throws aRangeErrorifcurrencyis missing in currency mode. - Assuming identical output across OS/Node ICU builds: Different browsers, operating systems, or Node.js ICU versions can vary slightly in spacing, narrow non-breaking spaces, or symbol vs. code rendering for specific locales—test critical display strings on your target runtimes.
- Using floating-point math for money arithmetic: Format after computing totals, and avoid
0.1 + 0.2binary floating-point drift in financial calculations by using integer cents/minor units or a dedicated decimal library.
TL;DR: Use new Intl.NumberFormat(locale, { style: "currency", currency: "USD" }).format(amount) with an explicit ISO currency code, customize currencyDisplay or notation as needed, and do monetary math before formatting.
Are you formatting prices for a specific locale/currency, using compact notation, or handling money math before display?
