Lesson 96 – JavaScript `Intl` Object: Internationalization API
The Intl
object in JavaScript is used for language-sensitive formatting such as numbers, dates, times, and currencies. It allows you to display data based on a user's locale.
What You'll Learn
- What the
Intl
object is - Formatting numbers and currencies
- Formatting dates and times
- Localizing text
1. Introduction to Intl
Intl
stands for Internationalization. It is a built-in object in JavaScript that provides tools to support:
- Date and time formatting
- Number formatting
- Currency formatting
- Plural rules, collators, and more
2. Formatting Numbers
const number = 1234567.89;
const formatted = new Intl.NumberFormat('en-US').format(number);
console.log(formatted); // "1,234,567.89"
Change the locale:
console.log(new Intl.NumberFormat('de-DE').format(number)); // "1.234.567,89"
3. Formatting Currencies
const price = 1499.99;
const usd = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(price);
console.log(usd); // "$1,499.99"
Change to Euro:
const euro = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR'
}).format(price);
console.log(euro); // "1.499,99 €"
4. Formatting Dates
const date = new Date();
const usDate = new Intl.DateTimeFormat('en-US').format(date);
console.log(usDate); // "4/30/2025"
Customize with options:
const formattedDate = new Intl.DateTimeFormat('en-GB', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
}).format(date);
console.log(formattedDate); // "Wednesday, 30 April 2025"
5. Formatting Time
const time = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: true
}).format(new Date());
console.log(time); // e.g., "2:45:30 PM"
6. Locale-Specific Comparisons
const collator = new Intl.Collator('en', { sensitivity: 'base' });
console.log(collator.compare('a', 'A')); // 0 (same)
Summary
Intl
helps adapt your app for global users.- Easily format numbers, currencies, and dates.
- Always consider the locale for better UX.
Try Your Hand
Task: Format today's date in French with full weekday and month.
const today = new Date();
const frenchDate = new Intl.DateTimeFormat('fr-FR', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
}).format(today);
console.log(frenchDate); // e.g., "mercredi 30 avril 2025"