Intl.DisplayNames.supportedLocalesOf() - JavaScript

Intl.DisplayNames.supportedLocalesOf()
======================================

The **`Intl.DisplayNames.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in display names without having to fall back to the runtime's default locale.

Syntax
------

```js
Intl.DisplayNames.supportedLocalesOf(locales)
Intl.DisplayNames.supportedLocalesOf(locales, options)
```

### Parameters

`locales`

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options` Optional

An object that may have the following property:

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the Intl page.

### Return value

An array of strings representing a subset of the given locale tags that are supported in display names without having to fall back to the runtime's default locale.

Examples
--------

### Using supportedLocalesOf()

Assuming a runtime that supports Indonesian and German but not Balinese in display names, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to display names nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.DisplayNames.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-Intl.DisplayNames.supportedLocalesOf |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DisplayNames`


Intl.DisplayNames() constructor - JavaScript

Intl.DisplayNames() constructor
===============================

The **`Intl.DisplayNames()`** constructor creates `Intl.DisplayNames` objects.

Try it
------

Syntax
------

```js
new Intl.DisplayNames(locales, options)
```

**Note:** `Intl.DisplayNames()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`.

### Parameters

`locales`

A string with a BCP 47 language tag or an `Intl.Locale` instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options`

An object containing the following properties, in the order they are retrieved:

`localeMatcher` Optional

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see Locale identification and negotiation.

`style` Optional

The formatting style to use. Possible values are `"narrow"`, `"short"`, and `"long"`; the default is `"long"`.

`type`

The type of display names to return from `of()`. Possible values are `"language"`, `"region"`, `"script"`, `"currency"`, `"calendar"`, and `"dateTimeField"`.

`fallback` Optional

What to return from `of()` if the input is structurally valid but there's no matching display name. Possible values are:

`"code"` (default)

Return the input code itself.

`"none"`

Return `undefined`.

`languageDisplay` Optional

How language names should be displayed. Only usable along with `type: "language"`. Possible values are:

`"dialect"` (default)

Display special regional dialects using their own name. E.g. `"nl-BE"` will be displayed as `"Flemish"`.

`"standard"`

Display all languages using standard format. E.g. `"nl-BE"` will be displayed as `"Dutch (Belgium)"`.

### Exceptions

`TypeError`

Thrown if `options.type` is not provided.

`RangeError`

Thrown if `locales` or `options` contain invalid values.

Examples
--------

### Basic usage

 In basic use without specifying a locale, a formatted string in the default locale and
 with default options is returned.

```js
console.log(new Intl.DisplayNames([], { type: "language" }).of("US"));
// 'us'
```

### Using type `dateTimeField`

Example using `dateTimeField` as a type option, will return the localized date time names strings.

```js
const dn = new Intl.DisplayNames("pt", { type: "dateTimeField" });
console.log(dn.of("era")); // 'era'
console.log(dn.of("year")); // 'ano'
console.log(dn.of("month")); // 'mês'
console.log(dn.of("quarter")); // 'trimestre'
console.log(dn.of("weekOfYear")); // 'semana'
console.log(dn.of("weekday")); // 'dia da semana'
console.log(dn.of("dayPeriod")); // 'AM/PM'
console.log(dn.of("day")); // 'dia'
console.log(dn.of("hour")); // 'hora'
console.log(dn.of("minute")); // 'minuto'
console.log(dn.of("second")); // 'segundo'
```

### Using type `calendar`

Example using `calendar` as a type option, will return the localized calendar names strings.

```js
const dn = new Intl.DisplayNames("en", { type: "calendar" });
console.log(dn.of("roc")); // 'Minguo Calendar'
console.log(dn.of("gregory")); // 'Gregorian Calendar'
console.log(dn.of("chinese")); // 'Chinese Calendar'
```

### Using type `language` with `languageDisplay`

Example using `language` as a type with `languageDisplay` options.

```js
// Using `dialect` option
const dnDialect = new Intl.DisplayNames("en", {
  type: "language",
  languageDisplay: "dialect",
});
console.log(dnDialect.of("en-GB")); // 'British English'

// Using `standard` option
const dnStd = new Intl.DisplayNames("en", {
  type: "language",
  languageDisplay: "standard",
});
console.log(dnStd.of("en-GB")); // 'English (United Kingdom)'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl-displaynames-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DisplayNames`
* `Intl.supportedValuesOf()`
* `Intl`


Intl.DisplayNames.prototype.of() - JavaScript

Intl.DisplayNames.prototype.of()
================================

The **`of()`** method of `Intl.DisplayNames` instances receives a code and returns a string based on the locale and options provided when instantiating this `Intl.DisplayNames` object.

Try it
------

Syntax
------

```js
of(code)
```

### Parameters

`code`

The `code` to provide depends on the `type`:

* If the type is "region", `code` should be either an two-letter ISO 3166 region code, or a three-digit UN M49 geographic region. It is required to follow the `unicode_region_subtag` grammar.
* If the type is "script", `code` should be an four-letter ISO 15924 script code. It is required to follow the `unicode_script_subtag` grammar.
* If the type is "language", `code` should be a *languageCode* ["-" *scriptCode*] ["-" *regionCode* ] \*("-" *variant* ) subsequence of the `unicode_language_id` grammar. *languageCode* is either a two-letter ISO 639-1 language code or a three-letter ISO 639-2 language code.
* If the type is "currency", `code` should be a three-letter ISO 4217 currency code. It is required to have exactly three alphabetic characters.
* If the type is "dateTimeField", `code` should be one of: `"era"`, `"year"`, `"quarter"`, `"month"`, `"weekOfYear"`, `"weekday"`, `"day"`, `"dayPeriod"`, `"hour"`, `"minute"`, `"second"`, `"timeZoneName"`.
* If the type is "calendar", `code` should be a calendar key. It is required to follow the `type` grammar of a Unicode locale identifier.

### Return value

A language-specific formatted string, or `undefined` if there's no data for the input and `fallback` is `"none"`.

**Note:** `fallback` is only used if `code` is structurally valid. See using fallback.

### Exceptions

`RangeError`

Thrown if `code` is not structurally valid for the given `type`.

Examples
--------

### Using the of method

```js
const regionNames = new Intl.DisplayNames("en", { type: "region" });
regionNames.of("419"); // "Latin America"

const languageNames = new Intl.DisplayNames("en", { type: "language" });
languageNames.of("fr"); // "French"

const currencyNames = new Intl.DisplayNames("en", { type: "currency" });
currencyNames.of("EUR"); // "Euro"
```

### Using fallback

When the `Intl.DisplayNames` is constructed with `fallback: "code"`, the `of()` method will return the `code` if the input looks structurally valid but there's no data for the input. If `fallback` is `"none"`, `undefined` is returned.

```js
console.log(
  new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZL"),
); // "ZL"

console.log(
  new Intl.DisplayNames("en", { type: "region", fallback: "none" }).of("ZL"),
); // undefined
```

However, this only applies if the `code` is structurally valid. For example, if `type` is `"region"` but `code` does not follow the `unicode_region_subtag` grammar (2 alphabetic characters or 3 numeric characters), a `RangeError` is directly thrown instead of using the fallback.

```js
console.log(
  new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZLC"),
); // throws RangeError: invalid value "ZLC" for option region
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-Intl.DisplayNames.prototype.of |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DisplayNames`


Intl.DisplayNames.prototype.resolvedOptions() - JavaScript

Intl.DisplayNames.prototype.resolvedOptions()
=============================================

 The **`resolvedOptions()`** method of `Intl.DisplayNames` instances
 returns a new object with properties reflecting the locale and style formatting
 options computed during the construction of this `Intl.DisplayNames`
 object.

Syntax
------

```js
resolvedOptions()
```

### Parameters

None.

### Return value

 An object with properties reflecting the locale and formatting options computed during
 the construction of the given `Intl.DisplayNames` object.

Description
-----------

The object returned by `resolvedOptions()` has the following properties:

`locale`

 The BCP 47 language tag for the locale actually used. If any Unicode extension
 values were requested in the input BCP 47 language tag that led to this locale,
 the key-value pairs that were requested and are supported for this locale are
 included in `locale`.

`style`

 The value provided for this property in the `options` argument of the
 constructor or the default value (`"long"`). Its value is either
 `"long"`, `"short"`, or `"narrow"`.

`type`

 The value provided for this property in the `options` argument of the
 constructor or the default value (`"language"`). Its value is either
 `"language"`, `"region"`, `"script"`, or
 `"currency"`.

`fallback`

 The value provided for this property in the options argument of the constructor or
 the default value (`"code"`). Its value is either `"code"`
 or `"none"`.

Examples
--------

### Using resolvedOptions

```js
const displayNames = new Intl.DisplayNames(["de-DE"], { type: "region" });

const usedOptions = displayNames.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.style); // "long"
console.log(usedOptions.type); // "region"
console.log(usedOptions.fallback); // "code"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-Intl.DisplayNames.prototype.resolvedOptions |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DisplayNames`


Intl.Segmenter() constructor - JavaScript

Intl.Segmenter() constructor
============================

The **`Intl.Segmenter()`** constructor creates `Intl.Segmenter` objects.

Try it
------

Syntax
------

```js
new Intl.Segmenter()
new Intl.Segmenter(locales)
new Intl.Segmenter(locales, options)
```

**Note:** `Intl.Segmenter()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`.

### Parameters

`locales` Optional

A string with a BCP 47 language tag or an `Intl.Locale` instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options` Optional

An object containing the following properties, in the order they are retrieved (all of them are optional):

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see Locale identification and negotiation.

`granularity`

How granularly should the input be split. Possible values are:

`"grapheme"` (default)

Split the input into segments at grapheme cluster (user-perceived character) boundaries, as determined by the locale.

`"word"`

Split the input into segments at word boundaries, as determined by the locale.

`"sentence"`

Split the input into segments at sentence boundaries, as determined by the locale.

### Return value

A new `Intl.Segmenter` instance.

### Exceptions

`RangeError`

Thrown if `locales` or `options` contain invalid values.

Examples
--------

### Basic usage

The following example shows how to count words in a string using the Japanese language (where splitting the string using `String` methods would have given an incorrect result).

```js
const text = "吾輩は猫である。名前はたぬき。";
const japaneseSegmenter = new Intl.Segmenter("ja-JP", { granularity: "word" });
console.log(
  [...japaneseSegmenter.segment(text)].filter((segment) => segment.isWordLike)
    .length,
);
// 8, as the text is segmented as '吾輩'|'は'|'猫'|'で'|'ある'|'。'|'名前'|'は'|'たぬき'|'。'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl-segmenter-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Intl.Segmenter.prototype.segment() - JavaScript

Intl.Segmenter.prototype.segment()
==================================

The **`segment()`** method of `Intl.Segmenter` instances segments a string according to the locale and granularity of this `Intl.Segmenter` object.

Try it
------

Syntax
------

```js
segment(input)
```

### Parameters

`input`

The text to be segmented as a string.

### Return value

A new iterable `Segments` object containing the segments of the input string, using the segmenter's locale and granularity.

Examples
--------

```js
// Create a locale-specific word segmenter
const segmenter = new Intl.Segmenter("fr", { granularity: "word" });

// Use it to get an iterator over the segments of a string
const input = "Moi ? N'est-ce pas ?";
const segments = segmenter.segment(input);

// Use that for segmentation
for (const { segment, index, isWordLike } of segments) {
  console.log(
    "segment at code units [%d, %d]: «%s»%s",
    index,
    index + segment.length,
    segment,
    isWordLike ? " (word-like)" : "",
  );
}
// segment at code units [0, 3]: «Moi» (word-like)
// segment at code units [3, 4]: « »
// segment at code units [4, 5]: «?»
// segment at code units [5, 6]: « »
// segment at code units [6, 11]: «N'est» (word-like)
// segment at code units [11, 12]: «-»
// segment at code units [12, 14]: «ce» (word-like)
// segment at code units [14, 15]: « »
// segment at code units [15, 18]: «pas» (word-like)
// segment at code units [18, 19]: « »
// segment at code units [19, 20]: «?»
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.segmenter.prototype.segment |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Intl.Segmenter.prototype.resolvedOptions() - JavaScript

Intl.Segmenter.prototype.resolvedOptions()
==========================================

The **`resolvedOptions()`** method of `Intl.Segmenter` instances returns a new object with properties reflecting the locale and granularity options computed during the initialization of this `Intl.Segmenter` object.

Try it
------

Syntax
------

```js
resolvedOptions()
```

### Parameters

None.

### Return value

 A new object with properties reflecting the locale and collation options computed
 during the initialization of the given `Intl.Segmenter` object.

Description
-----------

The resulting object has the following properties:

`locale`

 The BCP 47 language tag for the locale actually used. If any Unicode extension
 values were requested in the input BCP 47 language tag that led to this locale,
 the key-value pairs that were requested and are supported for this locale are
 included in `locale`.

`granularity`

 The value provided for this property in the `options` argument or filled
 in as the default.

Examples
--------

### Basic usage

```js
const spanishSegmenter = new Intl.Segmenter("es", { granularity: "sentence" });
const options = spanishSegmenter.resolvedOptions();
console.log(options.locale); // "es"
console.log(options.granularity); // "sentence"
```

### Default granularity

```js
const spanishSegmenter = new Intl.Segmenter("es");
const options = spanishSegmenter.resolvedOptions();
console.log(options.locale); // "es"
console.log(options.granularity); // "grapheme"
```

### Fallback locale

```js
const banSegmenter = new Intl.Segmenter("ban");
const options = banSegmenter.resolvedOptions();
console.log(options.locale);
// "fr" on a runtime where the Balinese locale
// is not supported and French is the default locale
console.log(options.granularity); // "grapheme"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.segmenter.prototype.resolvedoptions |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Intl.Segmenter.supportedLocalesOf() - JavaScript

Intl.Segmenter.supportedLocalesOf()
===================================

The **`Intl.Segmenter.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in segmentation without having to fall back to the runtime's default locale.

Try it
------

Syntax
------

```js
Intl.Segmenter.supportedLocalesOf(locales)
Intl.Segmenter.supportedLocalesOf(locales, options)
```

### Parameters

`locales`

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options` Optional

An object that may have the following property:

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the Intl page.

### Return value

An array of strings representing a subset of the given locale tags that are supported in segmentation without having to fall back to the runtime's default locale.

Examples
--------

### Using supportedLocalesOf()

Assuming a runtime that supports Indonesian and German but not Balinese in segmentation, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to segmentation nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.Segmenter.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.segmenter.supportedlocalesof |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.Segmenter`


Segments - JavaScript

Segments
========

A **`Segments`** object is an iterable collection of the segments of a text string. It is returned by a call to the `segment()` method of an `Intl.Segmenter` object.

Try it
------

Instance methods
----------------

`Segments.prototype.containing()`

Returns an object describing the segment in the original string that includes the code unit at a specified index.

`Segments.prototype[@@iterator]()`

Returns an iterator to iterate over the segments.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-segments-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.Segmenter`
* `Intl.Segmenter.prototype.segment()`


Segments.prototype[@@iterator]() - JavaScript

Segments.prototype[@@iterator]()
================================

The **`[@@iterator]()`** method of `Segments` instances implements the iterable protocol and allows `Segments` objects to be consumed by most syntaxes expecting iterables, such as the spread syntax and `for...of` loops. It returns a segments iterator object that yields data about each segment.

Try it
------

Syntax
------

```js
segments[Symbol.iterator]()
```

### Parameters

None.

### Return value

A new iterable iterator object that yields data about each segment. Each yielded object has the same properties as the object returned by the `containing()` method.

Examples
--------

### Iteration using for...of loop

Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes `Segments` objects iterable, and iterating syntaxes like the `for...of` loop automatically call this method to obtain the iterator to loop over.

```js
const segmenter = new Intl.Segmenter("zh-CN", { granularity: "word" });
const input = "你好，世界！我爱编程。";

for (const value of segmenter.segment(input)) {
  console.log(value);
}

/\*
{segment: '你好', index: 0, input: '你好，世界！我爱编程。', isWordLike: true}
{segment: '，', index: 2, input: '你好，世界！我爱编程。', isWordLike: false}
{segment: '世界', index: 3, input: '你好，世界！我爱编程。', isWordLike: true}
{segment: '！', index: 5, input: '你好，世界！我爱编程。', isWordLike: false}
{segment: '我', index: 6, input: '你好，世界！我爱编程。', isWordLike: true}
{segment: '爱', index: 7, input: '你好，世界！我爱编程。', isWordLike: true}
{segment: '编', index: 8, input: '你好，世界！我爱编程。', isWordLike: true}
{segment: '程', index: 9, input: '你好，世界！我爱编程。', isWordLike: true}
{segment: '。', index: 10, input: '你好，世界！我爱编程。', isWordLike: false}
\*/
```

### Manually hand-rolling the iterator

You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process.

```js
const segmenter = new Intl.Segmenter("fr", { granularity: "word" });
const input = "Moi ? N'est-ce pas ?";
const segments = segmenter.segment(input);
const iterator = segments[Symbol.iterator]();

let result = iterator.next();

while (!result.done) {
  console.log(result.value);
  result = iterator.next();
}

/\*
{segment: 'Moi', index: 0, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: ' ', index: 3, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: '?', index: 4, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: ' ', index: 5, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: "N'est", index: 6, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: '-', index: 11, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: 'ce', index: 12, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: ' ', index: 14, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: 'pas', index: 15, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: ' ', index: 18, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: '?', index: 19, input: "Moi ? N'est-ce pas ?", isWordLike: false}
\*/
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-%segmentsprototype%-@@iterator |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.Segmenter`
* `Intl.Segmenter.prototype.segment()`
* `Symbol.iterator`
* Iteration protocols


Segments.prototype.containing() - JavaScript

Segments.prototype.containing()
===============================

The **`containing()`** method of `Segments` instances returns an object describing the segment in the string that includes the code unit at the specified index.

Try it
------

Syntax
------

```js
containing(codeUnitIndex)
```

### Parameters

`codeUnitIndex` Optional

A number specifying the index of the code unit in the original input string. If the value is omitted, it defaults to `0`.

### Return value

An object describing the segment of the original string with the following properties, or `undefined` if the supplied index value is out of bounds.

`segment`

A string containing the segment extracted from the original input string.

`index`

The code unit index in the original input string at which the segment begins.

`input`

The complete input string that was segmented.

`isWordLike`

A boolean value only if `granularity` is `"word"`; otherwise, `undefined`. If `granularity` is `"word"`, then `isWordLike` is `true` when the segment is word-like (i.e., consists of letters/numbers/ideographs/etc.); otherwise, `false`.

Examples
--------

```js
// ┃0 1 2 3 4 5┃6┃7┃8┃9 ← code unit index
// ┃A l l o n s┃-┃y┃!┃ ← code unit
const input = "Allons-y!";

const segmenter = new Intl.Segmenter("fr", { granularity: "word" });
const segments = segmenter.segment(input);

let current = segments.containing();
// { index: 0, segment: "Allons", isWordLike: true }

current = segments.containing(4);
// { index: 0, segment: "Allons", isWordLike: true }

current = segments.containing(6);
// { index: 6, segment: "-", isWordLike: false }

current = segments.containing(current.index + current.segment.length);
// { index: 7, segment: "y", isWordLike: true }

current = segments.containing(current.index + current.segment.length);
// { index: 8, segment: "!", isWordLike: false }

current = segments.containing(current.index + current.segment.length);
// undefined
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-%segmentsprototype%.containing |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.Segmenter`
* `Intl.Segmenter.prototype.segment()`


Intl.ListFormat.prototype.formatToParts() - JavaScript

Intl.ListFormat.prototype.formatToParts()
=========================================

 The **`formatToParts()`** method of `Intl.ListFormat` instances
 returns an `Array` of objects representing the different components that
 can be used to format a list of values in a locale-aware fashion.

Try it
------

Syntax
------

```js
formatToParts(list)
```

### Parameters

`list`

An iterable object, such as an `Array`, to be formatted according to a locale.

### Return value

An `Array` of components which contains the formatted parts from the list.

Description
-----------

 Whereas `Intl.ListFormat.prototype.format()` returns a string being the formatted version
 of the list (according to the given locale and style options),
 `formatToParts()` returns an array of the different components of the
 formatted string.

 Each element of the resulting array has two properties: `type` and
 `value`. The `type` property may be either
 `"element"`, which refers to a value from the list, or
 `"literal"` which refers to a linguistic construct. The `value`
 property gives the content, as a string, of the token.

 The locale and style options used for formatting are given when constructing the
 `Intl.ListFormat` instance.

Examples
--------

### Using formatToParts

```js
const fruits = ["Apple", "Orange", "Pineapple"];
const myListFormat = new Intl.ListFormat("en-GB", {
  style: "long",
  type: "conjunction",
});

console.table(myListFormat.formatToParts(fruits));
// [
// { "type": "element", "value": "Apple" },
// { "type": "literal", "value": ", " },
// { "type": "element", "value": "Orange" },
// { "type": "literal", "value": ", and " },
// { "type": "element", "value": "Pineapple" }
// ]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-Intl.ListFormat.prototype.formatToParts |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.ListFormat`
* `Intl.ListFormat.prototype.format()`
* `Intl.RelativeTimeFormat.prototype.formatToParts()`
* `Intl.NumberFormat.prototype.formatToParts()`
* `Intl.DateTimeFormat.prototype.formatToParts()`


Intl.ListFormat.prototype.resolvedOptions() - JavaScript

Intl.ListFormat.prototype.resolvedOptions()
===========================================

 The **`resolvedOptions()`** method of `Intl.ListFormat` instances
 returns a new object with properties reflecting the locale and style formatting
 options computed during the construction of this `Intl.ListFormat` object.

Try it
------

Syntax
------

```js
resolvedOptions()
```

### Parameters

None.

### Return value

 An object with properties reflecting the locale and formatting options computed during
 the construction of the given `Intl.ListFormat` object.

Description
-----------

The object returned by `resolvedOptions()` has the following properties:

`locale`

 The BCP 47 language tag for the locale actually used. If any Unicode extension
 values were requested in the input BCP 47 language tag that led to this locale,
 the key-value pairs that were requested and are supported for this locale are
 included in `locale`.

`style`

 The value provided for this property in the `options` argument of the
 constructor or the default value (`"long"`). Its value is either
 `"long"`, `"short"`, or `"narrow"`.

`type`

 The value provided for this property in the `options` argument of the
 constructor or the default value (`"conjunction"`). Its value is either
 `"conjunction"`, `"disjunction"`, or `"unit"`.

Examples
--------

### Using resolvedOptions

```js
const deListFormatter = new Intl.ListFormat("de-DE", { style: "short" });

const usedOptions = de.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.style); // "short"
console.log(usedOptions.type); // "conjunction" (the default value)
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-Intl.ListFormat.prototype.resolvedoptions |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.ListFormat`
* `Intl.NumberFormat.prototype.resolvedOptions()`
* `Intl.Collator.prototype.resolvedOptions()`
* `Intl.DateTimeFormat.prototype.resolvedOptions()`
* `Intl.PluralRules.prototype.resolvedOptions()`


Intl.ListFormat.supportedLocalesOf() - JavaScript

Intl.ListFormat.supportedLocalesOf()
====================================

The **`Intl.ListFormat.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in list formatting without having to fall back to the runtime's default locale.

Syntax
------

```js
Intl.ListFormat.supportedLocalesOf(locales)
Intl.ListFormat.supportedLocalesOf(locales, options)
```

### Parameters

`locales`

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options` Optional

An object that may have the following property:

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the Intl page.

### Return value

An array of strings representing a subset of the given locale tags that are supported in list formatting without having to fall back to the runtime's default locale.

Examples
--------

### Using supportedLocalesOf()

Assuming a runtime that supports Indonesian and German but not Balinese in list formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to list formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.ListFormat.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-Intl.ListFormat.supportedLocalesOf |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.ListFormat`


Intl.ListFormat.prototype.format() - JavaScript

Intl.ListFormat.prototype.format()
==================================

 The **`format()`** method of `Intl.ListFormat` instances returns a string with a
 language-specific representation of the list.

Try it
------

Syntax
------

```js
format()
format(list)
```

### Parameters

`list`

An iterable object, such as an Array.

### Return value

A language-specific formatted string representing the elements of the list

Description
-----------

 The **`format()`** method returns a string that has been
 formatted based on parameters provided in the `Intl.ListFormat` object. The
 `locales` and `options` parameters customize the behavior of
 `format()` and let applications specify the language conventions that
 should be used to format the list.

Examples
--------

### Using format

The following example shows how to create a List formatter using the English language.

```js
const list = ["Motorcycle", "Bus", "Car"];

console.log(
  new Intl.ListFormat("en-GB", { style: "long", type: "conjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus and Car

console.log(
  new Intl.ListFormat("en-GB", { style: "short", type: "disjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus or Car

console.log(
  new Intl.ListFormat("en-GB", { style: "narrow", type: "unit" }).format(list),
);
// Motorcycle Bus Car
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-Intl.ListFormat.prototype.format |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.ListFormat`


Intl.ListFormat() constructor - JavaScript

Intl.ListFormat() constructor
=============================

The **`Intl.ListFormat()`** constructor creates `Intl.ListFormat` objects.

Try it
------

Syntax
------

```js
new Intl.ListFormat()
new Intl.ListFormat(locales)
new Intl.ListFormat(locales, options)
```

**Note:** `Intl.ListFormat()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`.

### Parameters

`locales` Optional

A string with a BCP 47 language tag or an `Intl.Locale` instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options` Optional

An object containing the following properties, in the order they are retrieved (all of them are optional):

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see Locale identification and negotiation.

`type`

Indicates the type of grouping. Possible values are:

`"conjunction"` (default)

For "and"-based grouping of the list items: "A, B, and C"

`"disjunction"`

For "or"-based grouping of the list items: "A, B, or C"

`"unit"`

For grouping the list items as a unit (neither "and"-based nor "or"-based): "A, B, C"

`style`

The grouping style (for example, whether list separators and conjunctions are included). Possible values are:

`"long"` (default)

E.g. "A, B, and C"

`"short"`

E.g. "A, B, C"

`"narrow"`

E.g. "A B C"

### Exceptions

`RangeError`

Thrown if `locales` or `options` contain invalid values.

Examples
--------

### Using format

The following example shows how to create a List formatter using the English language.

```js
const list = ["Motorcycle", "Bus", "Car"];

console.log(
  new Intl.ListFormat("en-GB", { style: "long", type: "conjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus and Car

console.log(new Intl.ListFormat("en-GB", { style: "long" }).format(list));
// Motorcycle, Bus and Car

console.log(new Intl.ListFormat("en-US", { style: "long" }).format(list));
// Motorcycle, Bus, and Car

console.log(
  new Intl.ListFormat("en-GB", { style: "short", type: "conjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus and Car

console.log(
  new Intl.ListFormat("en-US", { style: "short", type: "conjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus, & Car

console.log(
  new Intl.ListFormat("en-GB", { style: "narrow", type: "conjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus, Car

console.log(
  new Intl.ListFormat("en-GB", { style: "long", type: "disjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus or Car

console.log(
  new Intl.ListFormat("en-GB", { style: "short", type: "disjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus or Car

console.log(
  new Intl.ListFormat("en-GB", { style: "narrow", type: "disjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus or Car

console.log(new Intl.ListFormat("en-US", { style: "narrow" }).format(list));
// Motorcycle, Bus, Car

console.log(
  new Intl.ListFormat("en-GB", { style: "narrow", type: "unit" }).format(list),
);
// Motorcycle Bus Car

console.log(
  new Intl.ListFormat("en-US", { style: "long" }).format([
    "30 degrees",
    "15 minutes",
    "50 seconds",
  ]),
);
// 30 degrees, 15 minutes, and 50 seconds

console.log(
  new Intl.ListFormat("en-US", { style: "narrow" }).format([
    "30 degrees",
    "15 minutes",
    "50 seconds",
  ]),
);
// 30 degrees, 15 minutes, 50 seconds

console.log(
  new Intl.ListFormat("en-US", { style: "narrow", type: "unit" }).format([
    "30°",
    "15′",
    "50″",
  ]),
);
// 30° 15′ 50″
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl-listformat-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.ListFormat`
* `Intl`


Intl.NumberFormat.prototype.formatRangeToParts() - JavaScript

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

```js
formatRangeToParts(startRange, endRange)
```

### Parameters

`startRange`

A `Number` or `BigInt`.

`endRange`

A `Number` or `BigInt`.

### Return value

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

The structure of the returned looks like this:

```js
[
  { 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:

`currency`

The currency string, such as the symbols "$" and "€" or the name "Dollar", "Euro", depending on how `currencyDisplay` is specified.

`decimal`

The decimal separator string (".").

`fraction`

The fraction number.

`group`

The group separator string (",").

`infinity`

The `Infinity` string ("∞").

`integer`

The integer number.

`literal`

Any literal strings or whitespace in the formatted number.

`minusSign`

The minus sign string ("-").

`nan`

The `NaN` string ("NaN").

`plusSign`

The plus sign string ("+").

`percentSign`

The percent sign string ("%").

`unit`

The unit string, such as the "l" or "litres", depending on how `unitDisplay` is specified.

Possible values for the `source` property include:

`startRange`

The object is the start part of the range.

`endRange`

The object is the end part of the range.

`shared`

The object is a "shared" part of the range, such as a separator or currency.

### Exceptions

`RangeError`

Thrown if `startRange` is less than `endRange`, or either value is `NaN`.

`TypeError`

Thrown if either `startRange` or `endRange` is undefined.

Examples
--------

### Comparing formatRange and formatRangeToParts

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

```js
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:

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

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.numberformat.prototype.formatrangetoparts |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.NumberFormat`
* `Intl.NumberFormat.prototype.format()`
* `Intl.DateTimeFormat.prototype.formatRangeToParts()`


Intl.NumberFormat() constructor - JavaScript

Intl.NumberFormat() constructor
===============================

The **`Intl.NumberFormat()`** constructor creates `Intl.NumberFormat` objects.

Try it
------

Syntax
------

```js
new Intl.NumberFormat()
new Intl.NumberFormat(locales)
new Intl.NumberFormat(locales, options)

Intl.NumberFormat()
Intl.NumberFormat(locales)
Intl.NumberFormat(locales, options)
```

**Note:** `Intl.NumberFormat()` can be called with or without `new`. Both create a new `Intl.NumberFormat` instance. However, there's a special behavior when it's called without `new` and the `this` value is another `Intl.NumberFormat` instance; see Return value.

### Parameters

`locales` Optional

A string with a BCP 47 language tag or an `Intl.Locale` instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

The following Unicode extension key is allowed:

`nu`

See `numberingSystem`.

This key can also be set with `options` (as listed below). When both are set, the `options` property takes precedence.

`options` Optional

An object. For ease of reading, the property list is broken into sections based on their purposes, including locale options, style options, digit options, and other options.

#### Locale options

`localeMatcher`

 The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`.
 For information about this option, see Locale identification and negotiation.

`numberingSystem`

The numbering system to use for number formatting, such as `"arab"`, `"hans"`, `"mathsans"`, and so on. For a list of supported numbering system types, see `Intl.Locale.prototype.getNumberingSystems()`. This option can also be set through the `nu` Unicode extension key; if both are provided, this `options` property takes precedence.

#### Style options

Depending on the `style` used, some of them may be ignored, and others may be required:

`style`

The formatting style to use.

`"decimal"` (default)

For plain number formatting.

`"currency"`

For currency formatting.

`"percent"`

For percent formatting.

`"unit"`

For unit formatting.

`currency`

The currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as `"USD"` for the US dollar, `"EUR"` for the euro, or `"CNY"` for the Chinese RMB — see the Current currency & funds code list. There is no default value; if the `style` is `"currency"`, the `currency` property must be provided.

`currencyDisplay`

How to display the currency in currency formatting.

`"code"`

Use the ISO currency code.

`"symbol"` (default)

Use a localized currency symbol such as €.

`"narrowSymbol"`

Use a narrow format symbol ("$100" rather than "US$100").

`"name"`

Use a localized currency name such as `"dollar"`.

`currencySign`

In many locales, accounting format means to wrap the number with parentheses instead of appending a minus sign. Possible values are `"standard"` and `"accounting"`; the default is `"standard"`.

`unit`

The unit to use in `unit` formatting, Possible values are core unit identifiers, defined in UTS #35, Part 2, Section 6. A subset of units from the full list was selected for use in ECMAScript. Pairs of simple units can be concatenated with "-per-" to make a compound unit. There is no default value; if the `style` is `"unit"`, the `unit` property must be provided.

`unitDisplay`

The unit formatting style to use in `unit` formatting. Possible values are:

`"short"` (default)

E.g., `16 l`.

`"narrow"`

E.g., `16l`.

`"long"`

E.g., `16 litres`.

#### Digit options

The following properties are also supported by `Intl.PluralRules`.

`minimumIntegerDigits`

The minimum number of integer digits to use. A value with a smaller number of integer digits than this number will be left-padded with zeros (to the specified length) when formatted. Possible values are from `1` to `21`; the default is `1`.

`minimumFractionDigits`

The minimum number of fraction digits to use. Possible values are from `0` to `20`; the default for plain number and percent formatting is `0`; the default for currency formatting is the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information).

`maximumFractionDigits`

The maximum number of fraction digits to use. Possible values are from `0` to `20`; the default for plain number formatting is the larger of `minimumFractionDigits` and `3`; the default for currency formatting is the larger of `minimumFractionDigits` and the number of minor unit digits provided by the ISO 4217 currency code list (2 if the list doesn't provide that information); the default for percent formatting is the larger of `minimumFractionDigits` and 0.

`minimumSignificantDigits`

The minimum number of significant digits to use. Possible values are from `1` to `21`; the default is `1`.

`maximumSignificantDigits`

The maximum number of significant digits to use. Possible values are from `1` to `21`; the default is `21`.

The above properties fall into two groups: `minimumIntegerDigits`, `minimumFractionDigits`, and `maximumFractionDigits` in one group, `minimumSignificantDigits` and `maximumSignificantDigits` in the other. If properties from both groups are specified, conflicts in the resulting display format are resolved based on th value of the `roundingPriority` property.

`roundingPriority`

 Specify how rounding conflicts will be resolved if both "FractionDigits" (`minimumFractionDigits`/`maximumFractionDigits`) and "SignificantDigits" (`minimumSignificantDigits`/`maximumSignificantDigits`) are specified.
 Possible values are:

`"auto"` (default)

The result from the significant digits property is used.

`"morePrecision"`

The result from the property that results in more precision is used.

`"lessPrecision"`

The result from the property that results in less precision is used.

Note that for values other than `auto` the result with more precision is calculated from the `maximumSignificantDigits` and `maximumFractionDigits` (minimum fractional and significant digit settings are ignored).

`roundingIncrement`

Indicates the increment at which rounding should take place relative to the calculated rounding magnitude. Possible values are `1`, `2`, `5`, `10`, `20`, `25`, `50`, `100`, `200`, `250`, `500`, `1000`, `2000`, `2500`, and `5000`. It cannot be mixed with significant-digits rounding or any setting of `roundingPriority` other than `auto`.

`roundingMode`

How decimals should be rounded. Possible values are:

`"ceil"`

Round toward +∞. Positive values round up. Negative values round "more positive".

`"floor"`

Round toward -∞. Positive values round down. Negative values round "more negative".

`"expand"`

round away from 0. The *magnitude* of the value is always increased by rounding. Positive values round up. Negative values round "more negative".

`"trunc"`

Round toward 0. This *magnitude* of the value is always reduced by rounding. Positive values round down. Negative values round "less negative".

`"halfCeil"`

ties toward +∞. Values above the half-increment round like `"ceil"` (towards +∞), and below like `"floor"` (towards -∞). On the half-increment, values round like `"ceil"`.

`"halfFloor"`

Ties toward -∞. Values above the half-increment round like `"ceil"` (towards +∞), and below like `"floor"` (towards -∞). On the half-increment, values round like `"floor"`.

`"halfExpand"` (default)

Ties away from 0. Values above the half-increment round like `"expand"` (away from zero), and below like `"trunc"` (towards 0). On the half-increment, values round like `"expand"`.

`"halfTrunc"`

Ties toward 0. Values above the half-increment round like `"expand"` (away from zero), and below like `"trunc"` (towards 0). On the half-increment, values round like `"trunc"`.

`"halfEven"`

Ties towards the nearest even integer. Values above the half-increment round like `"expand"` (away from zero), and below like `"trunc"` (towards 0). On the half-increment values round towards the nearest even digit.

 These options reflect the ICU user guide, where "expand" and "trunc" map to ICU "UP" and "DOWN", respectively.
 The rounding modes example below demonstrates how each mode works.

`trailingZeroDisplay`

The strategy for displaying trailing zeros on whole numbers. Possible values are:

`"auto"` (default)

Keep trailing zeros according to `minimumFractionDigits` and `minimumSignificantDigits`.

`"stripIfInteger"`

Remove the fraction digits *if* they are all zero. This is the same as `"auto"` if any of the fraction digits is non-zero.

#### Other options

`notation`

The formatting that should be displayed for the number. Possible values are:

`"standard"` (default)

Plain number formatting.

`"scientific"`

Return the order-of-magnitude for formatted number.

`"engineering"`

Return the exponent of ten when divisible by three.

`"compact"`

String representing exponent; defaults to using the "short" form.

`compactDisplay`

Only used when `notation` is `"compact"`. Possible values are `"short"` and `"long"`; the default is `"short"`.

`useGrouping`

Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators.

`"always"`

Display grouping separators even if the locale prefers otherwise.

`"auto"`

Display grouping separators based on the locale preference, which may also be dependent on the currency.

`"min2"`

Display grouping separators when there are at least 2 digits in a group.

`true`

Same as `"always"`.

`false`

Display no grouping separators.

The default is `"min2"` if `notation` is `"compact"`, and `"auto"` otherwise. The string values `"true"` and `"false"` are accepted, but are always converted to the default value.

`signDisplay`

When to display the sign for the number. Possible values are:

`"auto"` (default)

Sign display for negative numbers only, including negative zero.

`"always"`

Always display sign.

`"exceptZero"`

Sign display for positive and negative numbers, but not zero.

`"negative"`

Sign display for negative numbers only, excluding negative zero.

`"never"`

Never display sign.

### Return value

A new `Intl.NumberFormat` object.

**Note:** The text below describes behavior that is marked by the specification as "optional". It may not work in all environments. Check the browser compatibility table.

Normally, `Intl.NumberFormat()` can be called with or without `new`, and a new `Intl.NumberFormat` instance is returned in both cases. However, if the `this` value is an object that is `instanceof` `Intl.NumberFormat` (doesn't necessarily mean it's created via `new Intl.NumberFormat`; just that it has `Intl.NumberFormat.prototype` in its prototype chain), then the value of `this` is returned instead, with the newly created `Intl.NumberFormat` object hidden in a `[Symbol(IntlLegacyConstructedSymbol)]` property (a unique symbol that's reused between instances).

```js
const formatter = Intl.NumberFormat.call(
  { \_\_proto\_\_: Intl.NumberFormat.prototype },
  "en-US",
  { notation: "scientific" },
);
console.log(Object.getOwnPropertyDescriptors(formatter));
// {
// [Symbol(IntlLegacyConstructedSymbol)]: {
// value: NumberFormat [Intl.NumberFormat] {},
// writable: false,
// enumerable: false,
// configurable: false
// }
// }
```

Note that there's only one actual `Intl.NumberFormat` instance here: the one hidden in `[Symbol(IntlLegacyConstructedSymbol)]`. Calling the `format()` and `resolvedOptions()` methods on `formatter` would correctly use the options stored in that instance, but calling all other methods (e.g. `formatRange()`) would fail with "TypeError: formatRange method called on incompatible Object", because those methods don't consult the hidden instance's options.

This behavior, called `ChainNumberFormat`, does not happen when `Intl.NumberFormat()` is called without `new` but with `this` set to anything else that's not an `instanceof Intl.NumberFormat`. If you call it directly as `Intl.NumberFormat()`, the `this` value is `Intl`, and a new `Intl.NumberFormat` instance is created normally.

### Exceptions

`RangeError`

Thrown in one of the following cases:

* A property that takes enumerated values (such as `style`, `units`, `currency`, and so on) is set to an invalid value.
* Both `maximumFractionDigits` and `minimumFractionDigits` are set, and they are set to different values.
 Note that depending on various formatting options, these properties can have default values.
 It is therefore possible to get this error even if you only set one of the properties.

`TypeError`

Thrown if the `options.style` property is set to "unit" or "currency", and no value has been set for the corresponding property `options.unit` or `options.currency`.

Examples
--------

### Basic usage

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

```js
const amount = 3500;

console.log(new Intl.NumberFormat().format(amount));
// '3,500' if in US English locale
```

### Decimal and percent formatting

```js
const amount = 3500;

new Intl.NumberFormat("en-US", {
  style: "decimal",
}).format(amount); // '3,500'
new Intl.NumberFormat("en-US", {
  style: "percent",
}).format(amount); // '350,000%'
```

### Unit formatting

 If the `style` is `'unit'`, a `unit` property must be provided.
 Optionally, `unitDisplay` controls the unit formatting.

```js
const amount = 3500;

new Intl.NumberFormat("en-US", {
  style: "unit",
  unit: "liter",
}).format(amount); // '3,500 L'

new Intl.NumberFormat("en-US", {
  style: "unit",
  unit: "liter",
  unitDisplay: "long",
}).format(amount); // '3,500 liters'
```

### Currency formatting

 If the `style` is `'currency'`, a `currency` property
 must be provided. Optionally, `currencyDisplay` and
 `currencySign` control the unit formatting.

```js
const amount = -3500;
new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
}).format(amount); // '-$3,500.00'

new Intl.NumberFormat("bn", {
  style: "currency",
  currency: "USD",
  currencyDisplay: "name",
}).format(amount); // '-3,500.00 US dollars'

new Intl.NumberFormat("bn", {
  style: "currency",
  currency: "USD",
  currencySign: "accounting",
}).format(amount); // '($3,500.00)'
```

### Scientific, engineering or compact notations

Scientific and compact notation are represented by the `notation` option and can be formatted like this:

```js
new Intl.NumberFormat("en-US", {
  notation: "scientific",
}).format(987654321);
// 9.877E8

new Intl.NumberFormat("pt-PT", {
  notation: "scientific",
}).format(987654321);
// 9,877E8

new Intl.NumberFormat("en-GB", {
  notation: "engineering",
}).format(987654321);
// 987.654E6

new Intl.NumberFormat("de", {
  notation: "engineering",
}).format(987654321);
// 987,654E6

new Intl.NumberFormat("zh-CN", {
  notation: "compact",
}).format(987654321);
// 9.9亿

new Intl.NumberFormat("fr", {
  notation: "compact",
  compactDisplay: "long",
}).format(987654321);
// 988 millions

new Intl.NumberFormat("en-GB", {
  notation: "compact",
  compactDisplay: "short",
}).format(987654321);
// 988M
```

### Displaying signs

Display a sign for positive and negative numbers, but not zero:

```js
new Intl.NumberFormat("en-US", {
  style: "percent",
  signDisplay: "exceptZero",
}).format(0.55);
// '+55%'
```

Note that when the currency sign is "accounting", parentheses might be used instead of a minus sign:

```js
new Intl.NumberFormat("bn", {
  style: "currency",
  currency: "USD",
  currencySign: "accounting",
  signDisplay: "always",
}).format(-3500);
// '($3,500.00)'
```

### FractionDigits, SignificantDigits and IntegerDigits

You can specify the minimum or maximum number of fractional, integer or significant digits to display when formatting a number.

**Note:** If both significant and fractional digit limits are specified, then the actual formatting depends on the `roundingPriority`.

#### Using FractionDigits and IntegerDigits

 The integer and fraction digit properties indicate the number of digits to display before and after the decimal point, respectively.
 If the value to display has fewer integer digits than specified, it will be left-padded with zeros to the expected number.
 If it has fewer fractional digits, it will be right-padded with zeros.
 Both cases are shown below:

```js
// Formatting adds zeros to display minimum integers and fractions
console.log(
  new Intl.NumberFormat("en", {
    minimumIntegerDigits: 3,
    minimumFractionDigits: 4,
  }).format(4.33),
);
// "004.3300"
```

 If a value has more fractional digits than the specified maximum number, it will be rounded.
 The *way* that it is rounded depends on the `roundingMode` property (more details are provided in the rounding modes section).
 Below the value is rounded from five fractional digits (`4.33145`) to two (`4.33`):

```js
// Display value shortened to maximum number of digits
console.log(
  new Intl.NumberFormat("en", {
    maximumFractionDigits: 2,
  }).format(4.33145),
);
// "4.33"
```

The minimum fractional digits have no effect if the value already has more than 2 fractional digits:

```js
// Minimum fractions have no effect if value is higher precision.
console.log(
  new Intl.NumberFormat("en", {
    minimumFractionDigits: 2,
  }).format(4.33145),
);
// "4.331"
```

**Warning:** Watch out for default values as they may affect formatting even if not specified in your code.
 The default maximum digit value is `3` for plain values, `2` for currency, and may have different values for other predefined types.

 The formatted value above is rounded to 3 digits, even though we didn't specify the maximum digits!
 This is because a default value of `maximumFractionDigits` is set when we specify `minimumFractionDigits`, and visa versa. The default values of `maximumFractionDigits` and `minimumFractionDigits` are `3` and `0`, respectively.

You can use `resolvedOptions()` to inspect the formatter.

```js
console.log(
  new Intl.NumberFormat("en", {
    maximumFractionDigits: 2,
  }).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumFractionDigits: 0,
// maximumFractionDigits: 2,
// …
// }

console.log(
  new Intl.NumberFormat("en", {
    minimumFractionDigits: 2,
  }).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumFractionDigits: 2,
// maximumFractionDigits: 3,
// …
// }
```

#### Using SignificantDigits

 The number of *significant digits* is the total number of digits including both integer and fractional parts.
 The `maximumSignificantDigits` is used to indicate the total number of digits from the original value to display.

 The examples below show how this works.
 Note in particular the last case: only the first digit is retained and the others are discarded/set to zero.

```js
// Display 5 significant digits
console.log(
  new Intl.NumberFormat("en", {
    maximumSignificantDigits: 5,
  }).format(54.33145),
);
// "54.331"

// Max 2 significant digits
console.log(
  new Intl.NumberFormat("en", {
    maximumSignificantDigits: 2,
  }).format(54.33145),
);
// "54"

// Max 1 significant digits
console.log(
  new Intl.NumberFormat("en", {
    maximumSignificantDigits: 1,
  }).format(54.33145),
);
// "50"
```

The `minimumSignificantDigits` ensures that at least the specified number of digits are displayed, adding zeros to the end of the value if needed.

```js
// Minimum 10 significant digits
console.log(
  new Intl.NumberFormat("en", {
    minimumSignificantDigits: 10,
  }).format(54.33145),
);
// "54.33145000"
```

**Warning:** Watch out for default values as they may affect formatting.
 If only one `SignificantDigits` property is used, then its counterpart will automatically be applied with the default value.
 The default maximum and minimum significant digit values are 20 and 1, respectively.

#### Specifying significant and fractional digits at the same time

 The fraction digits (`minimumFractionDigits`/`maximumFractionDigits`) and significant digits (`minimumSignificantDigits`/`maximumSignificantDigits`) are both ways of controlling how many fractional and leading digits should be formatted.
 If both are used at the same time, it is possible for them to conflict.

 These conflicts are resolved using the `roundingPriority` property.
 By default, this has a value of `"auto"`, which means that if either `minimumSignificantDigits` or `maximumSignificantDigits` is specified, the fractional and integer digit properties will be ignored.

 For example, the code below formats the value of `4.33145` with `maximumFractionDigits: 3`, and then `maximumSignificantDigits: 2`, and then both.
 The value with both is the one set with `maximumSignificantDigits`.

```js
console.log(
  new Intl.NumberFormat("en", {
    maximumFractionDigits: 3,
  }).format(4.33145),
);
// "4.331"
console.log(
  new Intl.NumberFormat("en", {
    maximumSignificantDigits: 2,
  }).format(4.33145),
);
// "4.3"
console.log(
  new Intl.NumberFormat("en", {
    maximumFractionDigits: 3,
    maximumSignificantDigits: 2,
  }).format(4.33145),
);
// "4.3"
```

Using `resolvedOptions()` to inspect the formatter, we can see that the returned object does not include `maximumFractionDigits` when `maximumSignificantDigits` or `minimumSignificantDigits` are specified.

```js
console.log(
  new Intl.NumberFormat("en", {
    maximumFractionDigits: 3,
    maximumSignificantDigits: 2,
  }).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumSignificantDigits: 1,
// maximumSignificantDigits: 2,
// …
// }
console.log(
  new Intl.NumberFormat("en", {
    maximumFractionDigits: 3,
    minimumSignificantDigits: 2,
  }).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumSignificantDigits: 2,
// maximumSignificantDigits: 21,
// …
// }
```

 In addition to `"auto"`, you can resolve conflicts by specifying `roundingPriority` as `"morePrecision"` or `"lessPrecision"`.
 The formatter calculates the precision using the values of `maximumSignificantDigits` and `maximumFractionDigits`.

The code below shows the format being selected for the three different rounding priorities:

```js
const maxFracNF = new Intl.NumberFormat("en", {
  maximumFractionDigits: 3,
});
console.log(`maximumFractionDigits:3 - ${maxFracNF.format(1.23456)}`);
// "maximumFractionDigits:2 - 1.235"

const maxSigNS = new Intl.NumberFormat("en", {
  maximumSignificantDigits: 3,
});
console.log(`maximumSignificantDigits:3 - ${maxSigNS.format(1.23456)}`);
// "maximumSignificantDigits:3 - 1.23"

const bothAuto = new Intl.NumberFormat("en", {
  maximumSignificantDigits: 3,
  maximumFractionDigits: 3,
});
console.log(`auto - ${bothAuto.format(1.23456)}`);
// "auto - 1.23"

const bothLess = new Intl.NumberFormat("en", {
  roundingPriority: "lessPrecision",
  maximumSignificantDigits: 3,
  maximumFractionDigits: 3,
});
console.log(`lessPrecision - ${bothLess.format(1.23456)}`);
// "lessPrecision - 1.23"

const bothMore = new Intl.NumberFormat("en", {
  roundingPriority: "morePrecision",
  maximumSignificantDigits: 3,
  maximumFractionDigits: 3,
});
console.log(`morePrecision - ${bothMore.format(1.23456)}`);
// "morePrecision - 1.235"
```

 Note that the algorithm can behave in an unintuitive way if a minimum value is specified without a maximum value.
 The example below formats the value `1` specifying `minimumFractionDigits: 2` (formatting to `1.00`) and `minimumSignificantDigits: 2` (formatting to `1.0`).
 Since `1.00` has more digits than `1.0`, this should be the result when prioritizing `morePrecision`, but in fact the opposite is true:

```js
const bothLess = new Intl.NumberFormat("en", {
  roundingPriority: "lessPrecision",
  minimumFractionDigits: 2,
  minimumSignificantDigits: 2,
});
console.log(`lessPrecision - ${bothLess.format(1)}`);
// "lessPrecision - 1.00"

const bothMore = new Intl.NumberFormat("en", {
  roundingPriority: "morePrecision",
  minimumFractionDigits: 2,
  minimumSignificantDigits: 2,
});
console.log(`morePrecision - ${bothMore.format(1)}`);
// "morePrecision - 1.0"
```

The reason for this is that only the "maximum precision" values are used for the calculation, and the default value of `maximumSignificantDigits` is much higher than `maximumFractionDigits`.

**Note:** The working group have proposed a modification of the algorithm where the formatter should evaluate the result of using the specified fractional and significant digits independently (taking account of both minimum and maximum values).
 It will then select the option that displays more fractional digits if `morePrecision` is set, and fewer if `lessPrecision` is set.
 This will result in more intuitive behavior for this case.

### Rounding modes

 If a value has more fractional digits than allowed by the constructor options, the formatted value will be *rounded* to the specified number of fractional digits.
 The *way* in which the value is rounded depends on the `roundingMode` property.

Number formatters use `halfExpand` rounding by default, which rounds values "away from zero" at the half-increment (in other words, the *magnitude* of the value is rounded up).

 For a positive number, if the fractional digits to be removed are closer to the next increment (or on the half way point) then the remaining fractional digits will be rounded up, otherwise they are rounded down.
 This is shown below: 2.23 rounded to two significant digits is truncated to 2.2 because 2.23 is less than the half increment 2.25, while values of 2.25 and greater are rounded up to 2.3:

```js
// Value below half-increment: round down.
console.log(
  new Intl.NumberFormat("en", {
    maximumSignificantDigits: 2,
  }).format(2.23),
);
// "2.2"

// Value on or above half-increment: round up.
console.log(
  new Intl.NumberFormat("en", {
    maximumSignificantDigits: 2,
  }).format(2.25),
);
console.log(
  new Intl.NumberFormat("en", {
    maximumSignificantDigits: 2,
  }).format(2.28),
);
// "2.3"
// "2.3"
```

A negative number on or below the half-increment point is also rounded away from zero (becomes more negative):

```js
// Value below half-increment: round down.
console.log(
  new Intl.NumberFormat("en", {
    maximumSignificantDigits: 2,
  }).format(-2.23),
);
// "-2.2"

// Value on or above half-increment: round up.
console.log(
  new Intl.NumberFormat("en", {
    maximumSignificantDigits: 2,
  }).format(-2.25),
);
console.log(
  new Intl.NumberFormat("en", {
    maximumSignificantDigits: 2,
  }).format(-2.28),
);
// "-2.3"
// "-2.3"
```

The table below show the effect of different rounding modes for positive and negative values that are on and around the half-increment.

| rounding mode | 2.23 | 2.25 | 2.28 | -2.23 | -2.25 | -2.28 |
| --- | --- | --- | --- | --- | --- | --- |
| `ceil` | 2.3 | 2.3 | 2.3 | -2.2 | -2.2 | -2.2 |
| `floor` | 2.2 | 2.2 | 2.2 | -2.3 | -2.3 | -2.3 |
| `expand` | 2.3 | 2.3 | 2.3 | -2.3 | -2.3 | -2.3 |
| `trunc` | 2.2 | 2.2 | 2.2 | -2.2 | -2.2 | -2.2 |
| `halfCeil` | 2.2 | 2.3 | 2.3 | -2.2 | -2.2 | -2.3 |
| `halfFloor` | 2.2 | 2.2 | 2.3 | -2.2 | -2.3 | -2.3 |
| `halfExpand` | 2.2 | 2.3 | 2.3 | -2.2 | -2.3 | -2.3 |
| `halfTrunc` | 2.2 | 2.2 | 2.3 | -2.2 | -2.2 | -2.3 |
| `halfEven` | 2.2 | 2.2 | 2.3 | -2.2 | -2.2 | -2.3 |

When using `halfEven`, its behavior also depends on the parity (odd or even) of the last digit of the rounded number. For example, the behavior of `halfEven` in the table above is the same as `halfTrunc`, because the magnitudes of all numbers are between a smaller "even" number (2.2) and a larger "odd" number (2.3). If the numbers are between ±2.3 and ±2.4, `halfEven` will behave like `halfExpand` instead. This behavior avoids consistently under- or over-estimating half-increments in a large data sample.

### Using roundingIncrement

 Sometimes we want to round the remaining fractional digits to some other increment than the next integer.
 For example, currencies for which the smallest coin is 5 cents might want to round the value to increments of 5, reflecting amounts that can actually be paid in cash.

This kind of rounding can be achieved with the `roundingIncrement` property.

For example, if `maximumFractionDigits` is 2 and `roundingIncrement` is 5, then the number is rounded to the nearest 0.05:

```js
const nf = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 2,
  roundingIncrement: 5,
});

console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.25"
console.log(nf.format(11.22)); // "$11.20"
```

 This particular pattern is referred to as "nickel rounding", where nickel is the colloquial name for a USA 5 cent coin.
 To round to the nearest 10 cents ("dime rounding"), you could change `roundingIncrement` to `10`.

```js
const nf = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 2,
  roundingIncrement: 5,
});

console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.25"
console.log(nf.format(11.22)); // "$11.20"
```

 You can also use `roundingMode` to change the rounding algorithm.
 The example below shows how `halfCeil` rounding can be used to round the value "less positive" below the half-rounding increment and "more positive" if above or on the half-increment.
 The incremented digit is "0.05" so the half-increment is at .025 (below, this is shown at 11.225).

```js
const nf = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 2,
  roundingIncrement: 5,
  roundingMode: "halfCeil",
});

console.log(nf.format(11.21)); // "$11.20"
console.log(nf.format(11.22)); // "$11.20"
console.log(nf.format(11.224)); // "$11.20"
console.log(nf.format(11.225)); // "$11.25"
console.log(nf.format(11.23)); // "$11.25"
```

If you need to change the number of digits, remember that `minimumFractionDigits` and `maximumFractionDigits` must both be set to the same value, or a `RangeError` is thrown.

`roundingIncrement` cannot be mixed with significant-digits rounding or any setting of `roundingPriority` other than `auto`.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl-numberformat-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.NumberFormat`
* `Intl.supportedValuesOf()`
* `Intl`


Intl.NumberFormat.prototype.formatToParts() - JavaScript

Intl.NumberFormat.prototype.formatToParts()
===========================================

The **`formatToParts()`** method of `Intl.NumberFormat` instances allows locale-aware formatting of strings produced by this `Intl.NumberFormat` object.

Try it
------

Syntax
------

```js
formatToParts()
formatToParts(number)
```

### Parameters

`number` Optional

A `Number` or `BigInt` to format.

### Return value

An `Array` of objects containing the formatted number in parts.

Description
-----------

 The `formatToParts()` method is useful for custom formatting of number
 strings. It returns an `Array` of objects containing the locale-specific
 tokens from which it possible to build custom strings while preserving the
 locale-specific parts. The structure the `formatToParts()` method returns,
 looks like this:

```js
[
  { type: "integer", value: "3" },
  { type: "group", value: "." },
  { type: "integer", value: "500" },
];
```

Possible types are the following:

`compact`

The exponent in `"long"` or `"short"` form, depending on how `compactDisplay` (which defaults to `short`) is specified when `notation` is set to `compact`.

`currency`

The currency string, such as the symbols "$" and "€" or the name "Dollar", "Euro", depending on how `currencyDisplay` is specified.

`decimal`

The decimal separator string (".").

`exponentInteger`

The exponent integer value, when `notation` is set to `scientific` or `engineering`.

`exponentMinusSign`

The exponent minus sign string ("-").

`exponentSeparator`

The exponent separator, when `notation` is set to `scientific` or `engineering`.

`fraction`

The fraction number.

`group`

The group separator string (",").

`infinity`

The `Infinity` string ("∞").

`integer`

The integer number.

`literal`

Any literal strings or whitespace in the formatted number.

`minusSign`

The minus sign string ("-").

`nan`

The `NaN` string ("NaN").

`plusSign`

The plus sign string ("+").

`percentSign`

The percent sign string ("%").

`unit`

The unit string, such as the "l" or "litres", depending on how `unitDisplay` is specified.

`unknown`

The string for `unknown` type results.

Examples
--------

### Comparing format and formatToParts

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

```js
const number = 3500;

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

formatter.format(number);
// "3.500,00 €"
```

 However, in many User Interfaces there is a desire to customize the formatting of this
 string. The `formatToParts` method enables locale-aware formatting of
 strings produced by `NumberFormat` formatters by providing you the string
 in parts:

```js
formatter.formatToParts(number);

// return value:
[
  { type: "integer", value: "3" },
  { type: "group", value: "." },
  { type: "integer", value: "500" },
  { type: "decimal", value: "," },
  { type: "fraction", value: "00" },
  { type: "literal", value: " " },
  { type: "currency", value: "€" },
];
```

 Now the information is available separately and it can be formatted and concatenated
 again in a customized way. For example by using `Array.prototype.map()`,
 arrow functions,
 a switch statement,
 template literals, and `Array.prototype.reduce()`.

```js
const numberString = formatter
  .formatToParts(number)
  .map(({ type, value }) => {
    switch (type) {
      case "currency":
        return `<strong>${value}</strong>`;
      default:
        return value;
    }
  })
  .reduce((string, part) => string + part);
```

This will make the currency bold, when using the `formatToParts()` method.

```js
console.log(numberString);
// "3.500,00 <strong>€</strong>"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.numberformat.prototype.formattoparts |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.NumberFormat`
* `Intl.NumberFormat.prototype.format()`
* `Intl.DateTimeFormat.prototype.formatToParts()`


Intl.NumberFormat.prototype.format() - JavaScript

Intl.NumberFormat.prototype.format()
====================================

The **`format()`** method of `Intl.NumberFormat` instances formats a number according to the locale and formatting options of this `Intl.NumberFormat` object.

Try it
------

Syntax
------

```js
format(number)
```

### Parameters

`number`

A `Number`, `BigInt`, or string, to format. Strings are parsed in the same way as in number conversion, except that `format()` will use the exact value that the string represents, avoiding loss of precision during implicitly conversion to a number.

**Note:** Older versions of the specification parsed strings as a `Number`.
 Check the compatibility table for your browser.

### Return value

A string representing the given `number` formatted according to the locale and formatting options of this `Intl.NumberFormat` object.

Description
-----------

`Number` values in JavaScript suffer from loss of precision if they are too big or too small, making the text representation inaccurate.
 If you are performing calculations with integers larger than `Number.MAX_SAFE_INTEGER` you should use a `BigInt` instead, which will format correctly:

```js
new Intl.NumberFormat("en-US").format(1234567891234567891); // 1,234,567,891,234,568,000
new Intl.NumberFormat("en-US").format(1234567891234567891n); // 1,234,567,891,234,567,891
```

You can also pass through very large strings to be formatted as an arbitrary-precision decimal string (if you're performing calculations on the data you will still need to work with `BigInt`):

```js
new Intl.NumberFormat("en-US").format("1234567891234567891"); // 1,234,567,891,234,567,891
```

Examples
--------

### Using format

 Use the `format` getter function for formatting a single currency value.
 The code below shows how to format the roubles currency for a Russian locale:

```js
const options = { style: "currency", currency: "RUB" };
const numberFormat = new Intl.NumberFormat("ru-RU", options);
console.log(numberFormat.format(654321.987));
// "654 321,99 ₽"
```

### Using format with map

 Use the `format` getter function for formatting all numbers in an array.
 Note that the function is bound to the `Intl.NumberFormat` from which it was obtained, so it can be passed directly to `Array.prototype.map`.
 This is considered a historical artefact, as part of a convention which is no longer followed for new features, but is preserved to maintain compatibility with existing programs.

```js
const a = [123456.789, 987654.321, 456789.123];
const numberFormat = new Intl.NumberFormat("es-ES");
const formatted = a.map((n) => numberFormat.format(n));
console.log(formatted.join("; "));
// "123.456,789; 987.654,321; 456.789,123"
```

### Using format with a string

Using a string we can specify very numbers that are larger than `Number.MAX_SAFE_INTEGER` without losing precision.

```js
const numberFormat = new Intl.NumberFormat("en-US");

// Here the value is converted to a Number
console.log(numberFormat.format(987654321987654321));
// 987,654,321,987,654,300

// Here we use a string and don't lose precision
console.log(numberFormat.format("987654321987654321"));
// 987,654,321,987,654,321
```

 We can also use the general "E" exponent syntax for decimal strings: `#.#E#`.
 The code below creates a `BigInt`, coerces it to a string with the suffix `E-6`, and then formats it.

```js
const numberFormat = new Intl.NumberFormat("en-US");
const bigNum = 1000000000000000110000n;
console.log(numberFormat.format(bigNum));
// "1,000,000,000,000,000,110,000"

// Format as a string using the `E` syntax:
console.log(numberFormat.format(`${bigNum}E-6`));
// "1,000,000,000,000,000.11"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.numberformat.prototype.format |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.NumberFormat`
* `Number.prototype.toLocaleString()`


Intl.NumberFormat.prototype.resolvedOptions() - JavaScript

Intl.NumberFormat.prototype.resolvedOptions()
=============================================

The **`resolvedOptions()`** method of `Intl.NumberFormat` instances returns a new object with properties reflecting the locale and number formatting options computed during initialization of this `Intl.NumberFormat` object.

Try it
------

Syntax
------

```js
resolvedOptions()
```

### Parameters

None.

### Return value

A new object with properties reflecting the locale and number formatting options computed during the construction of the given `Intl.NumberFormat` object.

The resulting object has the following properties:

`compactDisplay`

 Whether to use short or long form when using compact notation.
 This is the value provided in the `options.compactDisplay` argument of the constructor, or the default value: `"short"`.
 The value is only present if `notation` is set to "compact", and otherwise is `undefined`.

`currency`

 The currency to use in currency formatting.
 The value is defined if `style` is `"currency"`, and is otherwise `undefined`.
 This is the value provided in the `options.currency` argument of the constructor.

`currencyDisplay`

 The display format for the currency, such as a symbol, or currency code.
 The value is defined if `style` is `"currency"`, and otherwise is `undefined`.
 This is the value provided in the `options.currencyDisplay` argument of the constructor, or the default value: `"symbol"`.

`currencySign`

 The method used to specify the sign of the currency value: `standard` or `accounting`.
 The value is present if `style` is `"currency"`, and otherwise is `undefined`.
 This is the value provided in the `options.currencySign` argument of the constructor, or the default value: `"standard"`.

`locale`

 The BCP 47 language tag for the locale that was actually used.
 The key-value pairs that were requested in the constructor `locale` and are supported for this locale are included.

`notation`

 The formatting that should be applied to the number, such as `standard` or `engineering`.
 This is the value provided in the `options.notation` argument of the constructor, or the default value: `"standard"`.

`numberingSystem`

 The numbering system.
 This is the value provided in the `options.numberingSystem` argument of the constructor, if present, or the value set using the Unicode extension key `nu`, or filled in as a default.

`roundingMode`

 The rounding mode.
 This is the value provided for the `options.roundingMode` argument in the constructor, or the default value: `halfExpand`.

`roundingPriority`

 The priority for resolving rounding conflicts if both "FractionDigits" and "SignificantDigits" are specified.
 This is the value provided for the `options.roundingPriority` argument in the constructor, or the default value: `auto`.

`roundingIncrement`

 The rounding-increment precision (the increment used when rounding numbers).
 This is the value specified in the `options.roundingIncrement` argument in the constructor.

`signDisplay`

 Whether or not to display the positive/negative sign.
 This is the value specified in the `options.signDisplay` argument in the constructor, or the default value: `"auto"`.

`unit`

 The unit to use in unit formatting.
 The value is only present if `style` is `"unit"`, and is otherwise `undefined`.
 This is the value specified in the `options.unit` argument in the constructor.

`unitDisplay`

 The display format to use for units in unit formatting, such as "long", "short" or "narrow".
 The value is only present if `style` is `"unit"`, and is otherwise `undefined`.
 This is the value specified in the `options.unitDisplay` argument in the constructor, or the default value: `short`.

`useGrouping`

 Whether or not to use grouping separators to indicate "thousands", "millions" and son on.
 This is the value specified in the `options.useGrouping` argument in the constructor, or the default value: `"auto"`.

`trailingZeroDisplay`

 The strategy for displaying trailing zeros on whole numbers.
 This is the value specified in the `options.trailingZeroDisplay` argument in the constructor, or the default value: `"auto"`.

Only one of the following two groups of properties is included:

`minimumIntegerDigits`, `minimumFractionDigits`, `maximumFractionDigits`

 The values provided for these properties in the `options` argument or filled in as defaults.
 These properties are present only if neither `minimumSignificantDigits` nor `maximumSignificantDigits` was provided in the `options` argument.

`minimumSignificantDigits`, `maximumSignificantDigits`

 The values provided for these properties in the `options` argument or filled in as defaults.
 These properties are present only if at least one of them was provided in the `options` argument.

Examples
--------

### Using the `resolvedOptions` method

```js
// Create a NumberFormat
const de = new Intl.NumberFormat("de-DE", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 2,
  roundingIncrement: 5,
  roundingMode: "halfCeil",
});

// Resolve the options
const usedOptions = de.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.numberingSystem); // "latn"
console.log(usedOptions.compactDisplay); // undefined ("notation" not set to "compact")
console.log(usedOptions.currency); // "USD"
console.log(usedOptions.currencyDisplay); // "symbol"
console.log(usedOptions.currencySign); // "standard"
console.log(usedOptions.minimumIntegerDigits); // 1
console.log(usedOptions.minimumFractionDigits); // 2
console.log(usedOptions.maximumFractionDigits); // 2
console.log(usedOptions.minimumSignificantDigits); // undefined (maximumFractionDigits is set)
console.log(usedOptions.maximumSignificantDigits); // undefined (maximumFractionDigits is set)
console.log(usedOptions.notation); // "standard"
console.log(usedOptions.roundingIncrement); // 5
console.log(usedOptions.roundingMode); // halfCeil
console.log(usedOptions.roundingPriority); // auto
console.log(usedOptions.signDisplay); // "auto"
console.log(usedOptions.style); // "currency"
console.log(usedOptions.trailingZeroDisplay); // auto
console.log(usedOptions.useGrouping); // auto
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.numberformat.prototype.resolvedoptions |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.NumberFormat`


Intl.NumberFormat.supportedLocalesOf() - JavaScript

Intl.NumberFormat.supportedLocalesOf()
======================================

The **`Intl.NumberFormat.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in number formatting without having to fall back to the runtime's default locale.

Try it
------

Syntax
------

```js
Intl.NumberFormat.supportedLocalesOf(locales)
Intl.NumberFormat.supportedLocalesOf(locales, options)
```

### Parameters

`locales`

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options` Optional

An object that may have the following property:

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the Intl page.

### Return value

An array of strings representing a subset of the given locale tags that are supported in number formatting without having to fall back to the runtime's default locale.

Examples
--------

### Using supportedLocalesOf()

Assuming a runtime that supports Indonesian and German but not Balinese in number formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to number formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.NumberFormat.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.numberformat.supportedlocalesof |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.NumberFormat`


Intl.NumberFormat.prototype.formatRange() - JavaScript

Intl.NumberFormat.prototype.formatRange()
=========================================

The **`formatRange()`** method of `Intl.NumberFormat` instances formats a range of numbers according to the locale and formatting options of this `Intl.NumberFormat` object.

Syntax
------

```js
formatRange(startRange, endRange)
```

### Parameters

`startRange`

A `Number` or `BigInt`.

`endRange`

A `Number` or `BigInt`.

### Return value

A string representing the given range of numbers formatted according to the locale and formatting options of this `Intl.NumberFormat` object.

### Exceptions

`RangeError`

Thrown if `startRange` is less than `endRange`, or either value is `NaN`.

`TypeError`

Thrown if either `startRange` or `endRange` is undefined.

Description
-----------

The `formatRange` getter function formats a range of numbers into a string according to the locale and formatting options of this `Intl.NumberFormat` object from which it is called.

Examples
--------

### Using formatRange

Use the `formatRange` getter function for formatting a range of currency values:

```js
const nf = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  maximumFractionDigits: 0,
});

console.log(nf.formatRange(3, 5)); // "$3 – $5"

// Note: the "approximately equals" symbol is added if
// startRange and endRange round to the same values.
console.log(nf.formatRange(2.9, 3.1)); // "~$3"
```

```js
const nf = new Intl.NumberFormat("es-ES", {
  style: "currency",
  currency: "EUR",
  maximumFractionDigits: 0,
});

console.log(nf.formatRange(3, 5)); // "3-5 €"
console.log(nf.formatRange(2.9, 3.1)); // "~3 €"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.numberformat.prototype.formatrange |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.NumberFormat`
* `Number.prototype.toLocaleString()`


SyntaxError() constructor - JavaScript

SyntaxError() constructor
=========================

The **`SyntaxError()`** constructor creates `SyntaxError` objects.

Syntax
------

```js
new SyntaxError()
new SyntaxError(message)
new SyntaxError(message, options)
new SyntaxError(message, fileName)
new SyntaxError(message, fileName, lineNumber)

SyntaxError()
SyntaxError(message)
SyntaxError(message, options)
SyntaxError(message, fileName)
SyntaxError(message, fileName, lineNumber)
```

**Note:** `SyntaxError()` can be called with or without `new`. Both create a new `SyntaxError` instance.

### Parameters

`message` Optional

Human-readable description of the error

`options` Optional

An object that has the following properties:

`cause` Optional

 A property indicating the specific cause of the error.
 When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

`fileName` Optional
Non-standard

The name of the file containing the code that caused the exception

`lineNumber` Optional
Non-standard

The line number of the code that caused the exception

Examples
--------

### Catching a SyntaxError

```js
try {
  eval("hoo bar");
} catch (e) {
  console.log(e instanceof SyntaxError); // true
  console.log(e.message);
  console.log(e.name); // "SyntaxError"
  console.log(e.stack); // Stack of the error
}
```

### Creating a SyntaxError

```js
try {
  throw new SyntaxError("Hello");
} catch (e) {
  console.log(e instanceof SyntaxError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "SyntaxError"
  console.log(e.stack); // Stack of the error
}
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-nativeerror-constructors |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Error`


BigInt64Array() constructor - JavaScript

BigInt64Array() constructor
===========================

The **`BigInt64Array()`** constructor creates `BigInt64Array` objects. The contents are initialized to `0n`.

Syntax
------

```js
new BigInt64Array()
new BigInt64Array(length)
new BigInt64Array(typedArray)
new BigInt64Array(object)

new BigInt64Array(buffer)
new BigInt64Array(buffer, byteOffset)
new BigInt64Array(buffer, byteOffset, length)
```

**Note:** `BigInt64Array()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`.

### Parameters

See `TypedArray`.

### Exceptions

See `TypedArray`.

Examples
--------

### Different ways to create a BigInt64Array

```js
// From a length
const bigint64 = new BigInt64Array(2);
bigint64[0] = 42n;
console.log(bigint64[0]); // 42n
console.log(bigint64.length); // 2
console.log(bigint64.BYTES\_PER\_ELEMENT); // 8

// From an array
const x = new BigInt64Array([21n, 31n]);
console.log(x[1]); // 31n

// From another TypedArray
const y = new BigInt64Array(x);
console.log(y[0]); // 21n

// From an ArrayBuffer
const buffer = new ArrayBuffer(64);
const z = new BigInt64Array(buffer, 8, 4);
console.log(z.byteOffset); // 8

// From an iterable
const iterable = (function\* () {
  yield\* [1n, 2n, 3n];
})();
const bigint64FromIterable = new BigInt64Array(iterable);
console.log(bigint64FromIterable);
// BigInt64Array [1n, 2n, 3n]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-typedarray-constructors |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`
* `DataView`