How to format measurements like 5 kilometers or 10 pounds

Display distance, weight, temperature, and other measurements with locale-appropriate formatting and units

Introduction

Measurements communicate quantities with units that give them meaning. Five kilometers indicates a distance, ten pounds indicates a weight, and twenty degrees Celsius indicates a temperature. Applications that display measurements need to show both the numeric value and the unit in a format users understand.

Different locales format measurements differently. Americans write "5 km" or "5 kilometers" depending on context. Germans might write "5 km" with different spacing conventions. The same measurement can appear as "5 km", "5km", or "5 kilometers" depending on the locale and desired verbosity. Some regions use metric units while others use imperial units, but the formatting of units also varies by locale.

JavaScript provides the Intl.NumberFormat API to format measurements with locale-appropriate unit formatting. This lesson explains how to format measurements like distance, weight, temperature, volume, and speed with the correct unit display for any locale.

Measurements need units for context

Numbers without units lack meaning in many contexts. The number 5 could represent 5 kilometers, 5 miles, 5 meters, or 5 feet. Users cannot interpret the value without knowing the unit being measured.

Units must be displayed consistently with the numeric value. When you write "5 kilometers", the unit "kilometers" is essential information. When you write "10 pounds", the unit "pounds" identifies the measurement as weight rather than currency.

Different unit systems exist for the same type of measurement. Distance can be measured in kilometers, miles, meters, feet, or other units. Weight can be measured in kilograms, pounds, ounces, or grams. Temperature can be measured in Celsius, Fahrenheit, or Kelvin. Applications need to format whichever unit system they use in a way that matches user expectations.

Format units with Intl.NumberFormat

The Intl.NumberFormat constructor creates a unit formatter when you pass style: 'unit' in the options. You must also specify which unit to format using the unit option with a unit identifier.

const formatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer'
});

console.log(formatter.format(5));
// Output: "5 km"

This creates a formatter for US English that displays values in kilometers. The format() method converts the number to a string with the kilometer unit abbreviation.

The unit option accepts standardized unit identifiers. These identifiers use lowercase words separated by hyphens. Common identifiers include kilometer, meter, mile, pound, kilogram, celsius, fahrenheit, liter, and gallon.

const distanceFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer'
});

const weightFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'pound'
});

console.log(distanceFormatter.format(5));
// Output: "5 km"

console.log(weightFormatter.format(10));
// Output: "10 lb"

Each formatter automatically applies the appropriate unit abbreviation for the specified unit. You do not need to know which abbreviation corresponds to each unit identifier.

Locale determines unit formatting

The locale parameter controls how units are formatted, including spacing, separators, and unit abbreviations. The same unit produces different output depending on the locale.

const usFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer'
});

const deFormatter = new Intl.NumberFormat('de-DE', {
  style: 'unit',
  unit: 'kilometer'
});

const frFormatter = new Intl.NumberFormat('fr-FR', {
  style: 'unit',
  unit: 'kilometer'
});

console.log(usFormatter.format(5));
// Output: "5 km"

console.log(deFormatter.format(5));
// Output: "5 km"

console.log(frFormatter.format(5));
// Output: "5 km"

While kilometers use similar abbreviations across locales, spacing and separator conventions vary. The Intl API handles these locale-specific formatting rules automatically.

Control unit display verbosity

The unitDisplay option controls whether units appear in abbreviated, full, or minimal form. The option accepts three values: "short" for abbreviations, "long" for full unit names, and "narrow" for minimal display.

const shortFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer',
  unitDisplay: 'short'
});

const longFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer',
  unitDisplay: 'long'
});

const narrowFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer',
  unitDisplay: 'narrow'
});

console.log(shortFormatter.format(5));
// Output: "5 km"

console.log(longFormatter.format(5));
// Output: "5 kilometers"

console.log(narrowFormatter.format(5));
// Output: "5km"

The short format uses standard abbreviations like "km" or "lb". The long format uses full unit names like "kilometers" or "pounds". The narrow format uses minimal display with reduced or no spacing. The default is short when you do not specify unitDisplay.

The locale affects how long-form units appear. Full unit names are translated and adjusted for grammar rules in each language.

const enFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer',
  unitDisplay: 'long'
});

const deFormatter = new Intl.NumberFormat('de-DE', {
  style: 'unit',
  unit: 'kilometer',
  unitDisplay: 'long'
});

const esFormatter = new Intl.NumberFormat('es-ES', {
  style: 'unit',
  unit: 'kilometer',
  unitDisplay: 'long'
});

console.log(enFormatter.format(5));
// Output: "5 kilometers"

console.log(deFormatter.format(5));
// Output: "5 Kilometer"

console.log(esFormatter.format(5));
// Output: "5 kilómetros"

Each locale provides the appropriate translation and grammatical form for the unit name.

Format weight measurements

Weight measurements use unit identifiers like pound, kilogram, ounce, and gram. These identifiers work the same way as distance units.

const poundFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'pound'
});

const kilogramFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilogram'
});

console.log(poundFormatter.format(10));
// Output: "10 lb"

console.log(kilogramFormatter.format(10));
// Output: "10 kg"

You can format weight in long form to display full unit names.

const formatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'pound',
  unitDisplay: 'long'
});

console.log(formatter.format(1));
// Output: "1 pound"

console.log(formatter.format(10));
// Output: "10 pounds"

The formatter automatically handles singular and plural forms based on the value. One pound uses the singular form while ten pounds uses the plural form.

Format temperature measurements

Temperature measurements use unit identifiers like celsius and fahrenheit. These units format with degree symbols in short form.

const celsiusFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'celsius'
});

const fahrenheitFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'fahrenheit'
});

console.log(celsiusFormatter.format(20));
// Output: "20°C"

console.log(fahrenheitFormatter.format(68));
// Output: "68°F"

Long form displays the full temperature scale names.

const celsiusFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'celsius',
  unitDisplay: 'long'
});

const fahrenheitFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'fahrenheit',
  unitDisplay: 'long'
});

console.log(celsiusFormatter.format(20));
// Output: "20 degrees Celsius"

console.log(fahrenheitFormatter.format(68));
// Output: "68 degrees Fahrenheit"

Temperature formatting automatically includes the appropriate degree terminology for each scale.

Format volume measurements

Volume measurements use unit identifiers like liter, gallon, milliliter, and fluid-ounce. These work like other unit types.

const literFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'liter'
});

const gallonFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'gallon'
});

console.log(literFormatter.format(2));
// Output: "2 L"

console.log(gallonFormatter.format(2));
// Output: "2 gal"

Volume units also support long form display with locale-specific spelling.

const usFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'liter',
  unitDisplay: 'long'
});

const gbFormatter = new Intl.NumberFormat('en-GB', {
  style: 'unit',
  unit: 'liter',
  unitDisplay: 'long'
});

console.log(usFormatter.format(2));
// Output: "2 liters"

console.log(gbFormatter.format(2));
// Output: "2 litres"

The British English locale uses "litres" while American English uses "liters".

Format compound units

Compound units combine two simple units with a "per" relationship. Speed measurements like miles per hour or kilometers per hour use compound units. Fuel efficiency measurements like liters per 100 kilometers also use compound units.

Compound unit identifiers join two simple units with -per-. For example, mile-per-hour combines miles and hours, kilometer-per-hour combines kilometers and hours.

const mphFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'mile-per-hour'
});

const kphFormatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer-per-hour'
});

console.log(mphFormatter.format(60));
// Output: "60 mph"

console.log(kphFormatter.format(100));
// Output: "100 km/h"

Each compound unit formats with the appropriate abbreviation combining both unit parts.

Long form displays compound units with full names and locale-appropriate prepositions.

const formatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'mile-per-hour',
  unitDisplay: 'long'
});

console.log(formatter.format(60));
// Output: "60 miles per hour"

The formatter automatically constructs the compound unit phrase using the correct grammar for the locale.

Get available unit identifiers

The Intl.supportedValuesOf() method returns an array of all unit identifiers supported in your JavaScript environment. This method takes the string 'unit' as its argument.

const units = Intl.supportedValuesOf('unit');

console.log(units);
// Output: Array of unit identifiers like:
// ["acre", "bit", "byte", "celsius", "centimeter", "day",
//  "degree", "fahrenheit", "fluid-ounce", "foot", "gallon",
//  "gram", "hectare", "hour", "inch", "kilogram", "kilometer",
//  "liter", "meter", "mile", "millimeter", "ounce", "pound",
//  "second", "stone", "week", "yard", ...]

The returned array includes all simple units available for formatting. You can use any identifier from this array with the unit option.

This method helps when you need to verify whether a specific unit is supported or when you want to provide users with a list of available units.

const units = Intl.supportedValuesOf('unit');

const hasKilometer = units.includes('kilometer');
const hasPound = units.includes('pound');

console.log(hasKilometer);
// Output: true

console.log(hasPound);
// Output: true

You can check for specific units before creating formatters to handle environments with different support levels.

Combine with number formatting options

Unit formatters support the same number formatting options as other Intl.NumberFormat styles. You can control decimal places, significant digits, and other numeric properties.

const formatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer',
  maximumFractionDigits: 2
});

console.log(formatter.format(5.123));
// Output: "5.12 km"

console.log(formatter.format(5.5));
// Output: "5.5 km"

The formatter applies rounding and decimal place rules before adding the unit.

You can format large numbers with thousands separators.

const formatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer'
});

console.log(formatter.format(12345.67));
// Output: "12,345.67 km"

All standard number formatting features work with unit formatting.

Format measurements for user's locale

Instead of hardcoding a specific locale, you can use the user's browser language preferences. The navigator.language property returns the user's preferred locale.

const userLocale = navigator.language;

const formatter = new Intl.NumberFormat(userLocale, {
  style: 'unit',
  unit: 'kilometer'
});

console.log(formatter.format(5));
// Output varies by user's locale

This approach displays measurements according to each user's formatting expectations. Different users see the same measurement formatted according to their locale conventions.

Display measurements in applications

You can use unit formatters anywhere you display measurements to users. This includes fitness applications showing distance or weight, weather applications showing temperature, recipe applications showing volume, and navigation applications showing speed.

const distanceFormatter = new Intl.NumberFormat(navigator.language, {
  style: 'unit',
  unit: 'kilometer',
  maximumFractionDigits: 1
});

const distance = 5.234;

document.getElementById('distance').textContent = distanceFormatter.format(distance);
// Displays: "5.2 km" (or locale equivalent)

The formatted strings work like any other string value. You can insert them into text content, attributes, or any context where you display information to users.

Reusing unit formatters

Creating a new Intl.NumberFormat instance involves loading locale data and processing options. When you format multiple measurements with the same locale and unit, create the formatter once and reuse it.

const formatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'kilometer'
});

const distances = [1.5, 3.2, 5.0, 10.8];

distances.forEach(distance => {
  console.log(formatter.format(distance));
});
// Output:
// "1.5 km"
// "3.2 km"
// "5 km"
// "10.8 km"

This pattern is more efficient than creating a new formatter for each value. The performance difference becomes significant when formatting arrays or lists with many measurements.