Date, Number, and Currency Formatting
You'll learn how to use JavaScript's built-in Intl APIs to format dates, numbers, and currency values correctly for different regions without hardcoding regional conventions.
The Challenge of Regional Formats
Different regions display data differently: Americans write "12/31/2023" while Europeans write "31/12/2023"; numbers use different separators (1,000.50 vs 1.000,50); currency symbols vary ($ vs € vs ¥). Manually handling these variations is error-prone and endless.
The Intl Solution
JavaScript's Intl namespace provides three formatter objects that handle regional conventions automatically based on locale:
Intl.DateTimeFormat formats dates and times:
const locale = navigator.language; // e.g., 'en-US' or 'de-DE'
const dateFormatter = new Intl.DateTimeFormat(locale, {
year: 'numeric',
month: 'long',
day: 'numeric'
});
const date = new Date('2023-12-31');
console.log(dateFormatter.format(date));
// en-US: "December 31, 2023"
// de-DE: "31. Dezember 2023"
Intl.NumberFormat formats numbers with proper separators:
const numberFormatter = new Intl.NumberFormat(locale);
console.log(numberFormatter.format(1234567.89));
// en-US: "1,234,567.89"
// de-DE: "1.234.567,89"
Currency formatting uses NumberFormat with style options:
const currencyFormatter = new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'EUR'
});
console.log(currencyFormatter.format(1234.56));
// en-US: "€1,234.56"
// de-DE: "1.234,56 €"
These formatters respect the locale's conventions for symbol placement, grouping, and decimal separators automatically. You create them once (ideally cache them) and reuse for consistent formatting throughout your application.
Key Takeaway: Use Intl.DateTimeFormat, Intl.NumberFormat, and currency-specific NumberFormat options to automatically format values correctly for any region, eliminating manual formatting code and regional bugs.