Intl: formatting numbers and dates
A number and a date are stored in a form that has nothing to do with the way a reader writes them: 1234567.891 is a number and a date is a count of milliseconds. The Intl object turns both into text for a language and a region, with the separators, the currency symbol and the month names that the region uses.
Every example in this lesson passes its locale as an argument, which is the rule for a page like this one: a program that leaves the locale to the machine prints one thing on a server in Frankfurt and another on a laptop in London. The time zone is passed the same way, and the date below is built from Date.UTC so that the output does not depend on the clock of the machine either.
NumberFormat
Intl.NumberFormat takes a locale and an options object, and its format method turns a number into text. The same value comes out with commas in en-US and with dots and a comma in de-DE: the two conventions swap the roles of the two symbols. The currency, percent and unit styles add the symbol or the suffix that the locale prescribes.
const amount = 1234567.891;
console.log('en-US:', new Intl.NumberFormat('en-US').format(amount));
console.log('de-DE:', new Intl.NumberFormat('de-DE').format(amount));
console.log(
'dollars:',
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount)
);
console.log(
'percent:',
new Intl.NumberFormat('en-US', { style: 'percent' }).format(0.256)
);
console.log(
'speed:',
new Intl.NumberFormat('en-US', { style: 'unit', unit: 'kilometer-per-hour' }).format(88)
);
node numbers.js
en-US: 1,234,567.891
de-DE: 1.234.567,891
dollars: $1,234,567.89
percent: 26%
speed: 88 km/h
Two groupings of the same number, and the second is the reason a program does not write the separators itself: the dot and the comma swap places between the two conventions. A locale such as ru-RU goes further and groups with a no-break space, which looks like a plain space in the output and is a different character in the text. The percent style multiplies by a hundred, so 0.256 is written as a quarter and a bit over. Hard-coding a currency symbol is the other mistake, because its position and its spacing belong to the locale.
Options that shape the text
The options control the digits, the grouping, the sign and the notation. A minimum and a maximum number of fraction digits fix a price to two places, useGrouping turns the separators off for an identifier, and notation writes a million as 1.2M. The sign option makes a positive value carry a plus, which a change log wants.
const price = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 3,
});
console.log('price:', price.format(0.4567));
console.log('no grouping:', new Intl.NumberFormat('en-US', { useGrouping: false }).format(1234567.891));
console.log('compact:', new Intl.NumberFormat('en-US', { notation: 'compact' }).format(1234567));
console.log('sign:', new Intl.NumberFormat('en-US', { signDisplay: 'always' }).format(42));
console.log('rounded:', new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 }).format(2.5));
node options.js
price: 0.457
no grouping: 1234567.891
compact: 1.2M
sign: +42
rounded: 3
The price kept two digits where the value had four, and the compact form is the one a dashboard uses for a large count. The last line shows the rounding rule of the formatter: it sends a half away from zero, so two and a half becomes three and minus two and a half would become minus three, while Math.round in the lesson on rounding sends a half up and gives minus two. The formatter is formatting, not arithmetic, and the value it returns is a string.
DateTimeFormat
Intl.DateTimeFormat has the same shape: a locale, an options object and a format method that takes a date. The named styles, full, long, medium and short, pick the order of the parts and the words of the months, and timeZone decides which clock the value is read on.
const date = new Date(Date.UTC(2024, 4, 17, 15, 30));
console.log('ISO:', date.toISOString());
console.log(
'en-US full:',
new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeZone: 'UTC' }).format(date)
);
console.log(
'de-DE medium:',
new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeZone: 'UTC' }).format(date)
);
console.log(
'ru-RU long:',
new Intl.DateTimeFormat('ru-RU', { dateStyle: 'long', timeZone: 'UTC' }).format(date)
);
console.log(
'time:',
new Intl.DateTimeFormat('en-US', { timeStyle: 'short', timeZone: 'UTC' }).format(date)
);
console.log(
'both:',
new Intl.DateTimeFormat('en-US', {
dateStyle: 'short',
timeStyle: 'short',
timeZone: 'UTC',
}).format(date)
);
node dates.js
ISO: 2024-05-17T15:30:00.000Z
en-US full: Friday, May 17, 2024
de-DE medium: 17.05.2024
ru-RU long: 17 мая 2024 г.
time: 3:30 PM
both: 5/17/24, 3:30 PM
Three writings of one date, one of them in a language that names the month with its own word, and two that also show the clock. The timeZone is not decoration: without it the formatter uses the zone of the machine, and the same instant is the sixteenth in one place and the seventeenth in another. A stored timestamp is in UTC and a reader is somewhere else, so the zone is a decision the code has to make rather than leave to the runtime.
One formatter, many values
A formatter is an object with the locale and the options already resolved, and building one costs more than using it. The usual pattern is a formatter created once at the top of a module and called for every row of a table. formatToParts returns the pieces with their roles, which is how a program styles the currency symbol differently from the digits.
const dollars = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
console.log(dollars.format(12));
console.log(dollars.format(1234.5));
console.log(
dollars
.formatToParts(1234.5)
.map((part) => `${part.type}=${part.value}`)
.join(' ')
);
console.log(
'same options:',
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(12) ===
dollars.format(12)
);
node reuse.js
$12.00
$1,234.50
currency=$ integer=1 group=, integer=234 decimal=. fraction=50
same options: true
The two calls used one formatter and produced two amounts with the same conventions, and the parts list names each piece: the symbol, the integer part, the separator and the two decimals. The last line compares two formatters with the same options and finds the same text, which is why a formatter can be shared. This is the last lesson of the part, and the next part turns from values to the functions and the higher-order code that work on them.
Exercises
- Format -1234.5 with the dollars formatter in reuse.js. Where does the minus sign stand, and does the locale move it?
- Format the amount in numbers.js with the locale 'de-DE' and the euro. Which character stands between the number and the symbol?
- Ask for maximumFractionDigits: 0 on 2.5 and on -2.5. Which values arrive, and how does that differ from Math.round?
- Remove timeZone: 'UTC' from the first date line in dates.js and run the file in a zone other than UTC. Which part of the output changes?
- Count the parts of dollars.formatToParts(12). How many are there, and which one is missing compared with the amount that has cents?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does this program print?
console.log(new Intl.NumberFormat('en-US').format(1234567));Answer
1,234,567
The en-US convention groups thousands with commas, and the other conventions belong to other locales.
-
What does this program print?
console.log(new Intl.NumberFormat('en-US', { style: 'percent' }).format(0.25));Answer
25%
The percent style reads the value as a fraction and multiplies it by a hundred.
-
What does
style: 'currency'require besides the style?Answer
A currency code in the options
The style needs to know which currency, and the code such as USD or EUR is passed beside it.
-
What does this program print?
console.log(new Intl.NumberFormat('en-US', { useGrouping: false }).format(1234));Answer
1234
The option turns the separators off, which is what an identifier or a year wants.
-
What does this program print?
console.log(new Intl.NumberFormat('en-US', { notation: 'compact' }).format(1200000));Answer
1.2M
The compact notation writes the value with a suffix and a short mantissa.
-
What does
formatreturn?Answer
A string
The method formats for a reader, so its result is text; formatToParts is the array form.
-
Why does every example pass the locale explicitly?
Answer
Because the default comes from the machine and would differ between them
Without the argument the output follows the runtime, and a page cannot show a fixed output that way.
-
What does
timeZone: 'UTC'do in a DateTimeFormat?Answer
It reads the instant on the UTC clock
The zone decides which clock the instant is written on, and without it the machine decides.
-
What does this program print?
console.log(new Intl.NumberFormat('en-US', { signDisplay: 'always' }).format(7));Answer
+7
The option makes a positive value carry a plus sign.
-
What does
formatToPartsreturn?Answer
An array of the pieces with their roles
Each element names a type such as currency or integer and carries the text of that piece.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev