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.

JavascriptData Integrity

Code

javascriptsnippet
27 lines
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"
256MB

How 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

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`.