DEV3 Technologies home

DEV3 Developer Forum

How do I format currency and numbers in JavaScript for different locales?

JavaScript helpSolved0 views
dev3 ·

I format prices with toFixed(2) and manual commas, but it breaks for Indian grouping (1,00,000) and euro formats. What is the right API?

#javascript#intl#formatting

0

1 reply

dev3 · Accepted answer

Use the built-in Intl.NumberFormat. It knows grouping, decimal marks and currency placement for each locale.

const inr = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' });
inr.format(1234567.5);   // ₹12,34,567.50

new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(1234.5);
// 1.234,50 €

new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(1234.5);
// $1,234.50

Useful options

// compact: 1.2K, 3.4M
new Intl.NumberFormat('en', { notation: 'compact' }).format(1234567);   // 1.2M

// percent
new Intl.NumberFormat('en', { style: 'percent', maximumFractionDigits: 1 }).format(0.256); // 25.6%

// units
new Intl.NumberFormat('en', { style: 'unit', unit: 'kilometer-per-hour' }).format(80);

// digits
{ minimumFractionDigits: 2, maximumFractionDigits: 2 }

Create the formatter once and reuse it (construction is the expensive part).

Dates, plurals and lists

new Intl.DateTimeFormat('en-GB', { dateStyle: 'long' }).format(new Date());
new Intl.RelativeTimeFormat('en', { numeric: 'auto' }).format(-1, 'day'); // yesterday
new Intl.PluralRules('en').select(1);                                        // 'one'
new Intl.ListFormat('en', { type: 'conjunction' }).format(['a', 'b', 'c']);  // a, b, and c

Money rules

  1. Never use floating point for money maths: 0.1 + 0.2 !== 0.3. Store integer minor units (cents, paise) and divide only to display.
  2. toFixed returns a string and rounds with binary quirks (1.005.toFixed(2) gives 1.00).
  3. Currency decimals vary (JPY has 0, KWD has 3); Intl handles that per currency code.

Pitfall: server and browser may format differently if their default locale differs. Pass the locale explicitly to avoid hydration mismatches in React/Next.js.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.