UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ Intl/ NumberFormat/ Intl.NumberFormat.prototype.formatRangeToParts()

The formatRangeToParts() method of Intl.NumberFormat instances returns an Array of objects containing the locale-specific tokens from which it is possible to build custom strings while preserving the locale-specific parts. This makes it possible to provide locale-aware custom formatting ranges of number strings.

Syntax

formatRangeToParts(startRange, endRange)

Parameters

Return value

An Array of objects containing the formatted range of numbers in parts.

The structure of the returned looks like this:

[
  { type: "integer", value: "3", source: "startRange" },
  { type: "literal", value: "-", source: "shared" },
  { type: "integer", value: "5", source: "endRange" },
  { type: "literal", value: " ", source: "shared" },
  { type: "currency", value: "€", source: "shared" },
];

Possible values for the type property include:

Possible values for the source property include:

Exceptions

Examples

Comparing formatRange and formatRangeToParts

NumberFormat outputs localized, opaque strings that cannot be manipulated directly:

const startRange = 3500;
const endRange = 9500;

const formatter = new Intl.NumberFormat("de-DE", {
  style: "currency",
  currency: "EUR",
});

console.log(formatter.formatRange(startRange, endRange));
// "3.500,00–9.500,00 €"

However, for many user interfaces there is a need to customize the formatting of this string. The formatRangeToParts method enables locale-aware formatting of strings produced by NumberFormat formatters by providing you the string in parts:

console.log(formatter.formatRangeToParts(startRange, endRange));

// return value:
[
  { type: "integer", value: "3", source: "startRange" },
  { type: "group", value: ".", source: "startRange" },
  { type: "integer", value: "500", source: "startRange" },
  { type: "decimal", value: ",", source: "startRange" },
  { type: "fraction", value: "00", source: "startRange" },
  { type: "literal", value: "–", source: "shared" },
  { type: "integer", value: "9", source: "endRange" },
  { type: "group", value: ".", source: "endRange" },
  { type: "integer", value: "500", source: "endRange" },
  { type: "decimal", value: ",", source: "endRange" },
  { type: "fraction", value: "00", source: "endRange" },
  { type: "literal", value: " ", source: "shared" },
  { type: "currency", value: "€", source: "shared" },
];

Specifications

Browser compatibility

See also