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?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
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?
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
// 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).
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
0.1 + 0.2 !== 0.3. Store integer minor units (cents, paise) and divide only to display.toFixed returns a string and rounds with binary quirks (1.005.toFixed(2) gives 1.00).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.