Intl.NumberFormat Unit Styles Format Measurements
Format measurements with Intl.NumberFormat unit style, switch display modes, and use formatToParts to separate the number from its unit.
Code
const distance = new Intl.NumberFormat("en-US", {
style: "unit",
unit: "kilometer",
unitDisplay: "long",
maximumFractionDigits: 1,
});
console.log(distance.format(12.34));
console.log(distance.format(0.5));
const speed = new Intl.NumberFormat("en-US", {
style: "unit",
unit: "kilometer-per-hour",
unitDisplay: "short",
});
console.log(speed.format(88));
for (const part of distance.formatToParts(12.34)) {
console.log(part.type + ":", JSON.stringify(part.value));
}
const storage = new Intl.NumberFormat("en-US", {
style: "unit",
unit: "megabyte",
unitDisplay: "narrow",
});
console.log(storage.format(256));Output
Captured from a sandboxed run of this snippet in the build pipeline.
12.3 kilometers
0.5 kilometers
88 km/h
integer: "12"
decimal: "."
fraction: "3"
literal: " "
unit: "kilometers"
256MBHow it works
A single loop drives the file — for (const part of distance.formatToParts(12.34)).
The demo data lives in module-level bindings: distance, speed, storage.
What to watch for
- Runs on the standard library alone; nothing to install.
Key statements
const distance = new Intl.NumberFormat("en-US", {
style: "unit",
unit: "kilometer",
unitDisplay: "long",
maximumFractionDigits: 1,
});
const storage = new Intl.NumberFormat("en-US", {
style: "unit",
unit: "megabyte",
unitDisplay: "narrow",
});
const speed = new Intl.NumberFormat("en-US", {
style: "unit",
unit: "kilometer-per-hour",
unitDisplay: "short",
});
Interactive Tools for This Topic
CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `distance`, `speed`, `storage`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.