formatUnit()function

formatUnit(num: number, unit: string, options?: UnitFormatOptions): string
ParamType
numnumber
Quantity to format. required
unitstring
Unit reference to format the quantity as, e.g. "minute" or "product". required
optionsUnitFormatOptions
Formatting options including custom one/many/abbr strings for unsupported units.
    .onestring
String for one of this thing, e.g. product or item or sheep
- Used for unitDisplay: "long" formatting.
- Defaults to unit reference, e.g. "minute" readonly
    .manystring
String for several of this thing, e.g. products or items or sheep
- Used for unitDisplay: "long" formatting.
- Defaults to one + "s" readonly
    .abbrstring
Abbreviation for this thing, e.g. products or items or sheep (defaults to one + "s").
- Used for unitDisplay: "narrow" formatting.
- Defaults to unit reference, e.g. "minute" readonly
Return
string
Formatted quantity string, e.g. "5 minutes" or "5 products".

Format a quantity of a given unit.

  • Javascript has built-in support for formatting a number of different units.
  • Unfortunately the list of supported units changes in different browsers.
  • Ideally we want to format units using the built-in formatting so things like translation and internationalisation are covered.
  • But we want provide fallback formatting for unsupported units, and do something good enough job in most cases.

Examples

formatUnit(5, "minute", { unitDisplay: "long" }) // "5 minutes"