Unit Formatting with Intl.NumberFormat (Meters, Liters, Bytes)
Format measurement units like kilometers, liters, kilograms, and bytes for any locale using Intl.NumberFormat unit style. Learn about unitDisplay modes and supported unit identifiers.
Detailed Explanation
Formatting Units with Intl.NumberFormat
The unit style in Intl.NumberFormat formats values with locale-appropriate unit labels. It supports physical measurements, digital storage, speed, temperature, and more.
Basic Unit Formatting
new Intl.NumberFormat('en-US', {
style: 'unit', unit: 'kilometer', unitDisplay: 'long',
}).format(42); // "42 kilometers"
new Intl.NumberFormat('de-DE', {
style: 'unit', unit: 'kilometer', unitDisplay: 'long',
}).format(42); // "42 Kilometer"
new Intl.NumberFormat('ja-JP', {
style: 'unit', unit: 'kilometer', unitDisplay: 'long',
}).format(42); // "42 キロメートル"
Unit Display Modes
The unitDisplay option controls the label format:
const opts = { style: 'unit', unit: 'liter' };
// "long": "3.5 liters"
// "short": "3.5 L"
// "narrow": "3.5L"
Supported Unit Identifiers
Common units include:
- Length:
meter,kilometer,centimeter,millimeter,mile,yard,foot,inch - Mass:
kilogram,gram,milligram,pound,ounce - Volume:
liter,milliliter,gallon,fluid-ounce - Temperature:
celsius,fahrenheit - Speed:
kilometer-per-hour,mile-per-hour,meter-per-second - Digital:
byte,kilobyte,megabyte,gigabyte,terabyte - Duration:
year,month,week,day,hour,minute,second
Compound Units
You can combine two units with -per-:
new Intl.NumberFormat('en-US', {
style: 'unit',
unit: 'liter-per-100-kilometer',
unitDisplay: 'long',
}).format(5.8); // "5.8 liters per 100 kilometers"
new Intl.NumberFormat('en-US', {
style: 'unit',
unit: 'mile-per-gallon',
unitDisplay: 'short',
}).format(30); // "30 mpg"
Combining with Number Options
Unit formatting respects all other Intl.NumberFormat options:
new Intl.NumberFormat('en-US', {
style: 'unit',
unit: 'megabyte',
unitDisplay: 'short',
notation: 'compact',
}).format(1500); // "1.5K MB"
Use Case
Unit formatting is essential for applications that display physical measurements, file sizes, or speed values to international users. A fitness app showing running distances needs to display '5 km' in metric locales and '3.1 mi' in imperial locales. A cloud storage dashboard showing file sizes needs '1.5 GB' in English and '1,5 Go' in French. Using unit formatting ensures labels are translated and formatted correctly for every locale.
Try It — Locale String Tester
Related Topics
Intl.NumberFormat Basics: Locale-Aware Number Formatting
Intl.NumberFormat
Compact Number Notation (1K, 1M, 1B) with Intl.NumberFormat
Intl.NumberFormat
Number Grouping Styles by Locale: Indian, Western, and East Asian
Intl.NumberFormat
Currency Formatting by Locale with Intl.NumberFormat
Intl.NumberFormat
Percent Formatting with Intl.NumberFormat
Intl.NumberFormat