Number.NaN

Number.NaN
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The Number.NaN
static data property represents Not-A-Number, which is equivalent to NaN
. For more information about the behaviors of NaN
, see the description for the global property.
Try it
function clean(x) {
if (x === Number.NaN) {
// Can never be true
return null;
}
if (isNaN(x)) {
return 0;
}
}
console.log(clean(Number.NaN));
// Expected output: 0
Value
The number value NaN
.
Property attributes of Number.NaN | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
Because NaN
is a static property of Number
, you always use it as Number.NaN
, rather than as a property of a number value.
Examples
Checking whether values are numeric
js
function sanitize(x) {
if (isNaN(x)) {
return Number.NaN;
}
return x;
}
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-number.nan |


Number.MIN_VALUE

Number.MIN_VALUE
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The Number.MIN_VALUE
static data property represents the smallest positive numeric value representable in JavaScript.
Try it
function divide(x, y) {
if (x / y < Number.MIN_VALUE) {
return "Process as 0";
}
return x / y;
}
console.log(divide(5e-324, 1));
// Expected output: 5e-324
console.log(divide(5e-324, 2));
// Expected output: "Process as 0"
Value
2-1074, or 5E-324
.
Property attributes of Number.MIN_VALUE | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
Number.MIN_VALUE
is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, "must be the smallest non-zero positive value that can actually be represented by the implementation". This is because small IEEE-754 floating point numbers are denormalized, but implementations are not required to support this representation, in which case Number.MIN_VALUE
may be larger.
In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or 5E-324
.
Because MIN_VALUE
is a static property of Number
, you always use it as Number.MIN_VALUE
, rather than as a property of a number value.
Examples
Using MIN_VALUE
The following code divides two numeric values. If the result is greater than or equal to MIN_VALUE
, the func1
function is called; otherwise, the func2
function is called.
if (num1 / num2 >= Number.MIN_VALUE) {
func1();
} else {
func2();
}
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-number.min_value |


Date.prototype.valueOf()

Date.prototype.valueOf()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The valueOf()
method of Date
instances returns the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.
Try it
const date1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));
console.log(date1.valueOf());
// Expected output: 823230245000
const date2 = new Date("02 Feb 1996 03:04:05 GMT");
console.log(date2.valueOf());
// Expected output: 823230245000
Syntax
valueOf()
Parameters
None.
Return value
A number representing the timestamp, in milliseconds, of this date. Returns NaN
if the date is invalid.
Description
The valueOf()
method is part of the type coercion protocol. Because Date
has a [Symbol.toPrimitive]()
method, that method always takes priority over valueOf()
when a Date
object is implicitly coerced to a number. However, Date.prototype[Symbol.toPrimitive]()
still calls this.valueOf()
internally.
The Date
object overrides the valueOf()
method of Object
. Date.prototype.valueOf()
returns the timestamp of the date, which is functionally equivalent to the Date.prototype.getTime()
method.
Examples
Using valueOf()
const d = new Date(0); // 1970-01-01T00:00:00.000Z
console.log(d.valueOf()); // 0
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-date.prototype.valueof |


Date.prototype.toTimeString()

Date.prototype.toTimeString()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The toTimeString()
method of Date
instances returns a string representing the time portion of this date interpreted in the local timezone.
Try it
const event = new Date("August 19, 1975 23:15:30");
console.log(event.toTimeString());
// Expected output: "23:15:30 GMT+0200 (CEST)"
// Note: your timezone may vary
Syntax
js
toTimeString()
Parameters
None.
Return value
A string representing the time portion of the given date (see description for the format). Returns "Invalid Date"
if the date is invalid.
Description
Date
instances refer to a specific point in time. toTimeString()
interprets the date in the local timezone and formats the time part in English. It always uses the format of HH:mm:ss GMT±xxxx (TZ)
, where:
| Format String | Description |
|---|---|
HH |
Hour, as two digits with leading zero if required |
mm |
Minute, as two digits with leading zero if required |
ss |
Seconds, as two digits with leading zero if required |
±xxxx |
The local timezone's offset — two digits for hours and two digits for minutes (e.g., -0500 , +0800 ) |
TZ |
The timezone's name (e.g., PDT , PST ) |
For example: "04:42:04 GMT+0000 (Coordinated Universal Time)".
- If you only want to get the date part, use
toDateString()
. - If you want to get both the date and time, use
toString()
. - If you want to make the date interpreted as UTC instead of local timezone, use
toUTCString()
. - If you want to format the date in a more user-friendly format (e.g., localization), use
toLocaleTimeString()
.
Examples
Using toTimeString()
js
const d = new Date(0);
console.log(d.toString()); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
console.log(d.toTimeString()); // "00:00:00 GMT+0000 (Coordinated Universal Time)"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-date.prototype.totimestring |


Date.prototype.toTemporalInstant()

Date.prototype.toTemporalInstant()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The toTemporalInstant()
method of Date
instances returns a new Temporal.Instant
object with the same epochMilliseconds
value as this date's timestamp.
Use this method to convert legacy Date
values to the Temporal
API, then further convert it to other Temporal
classes as necessary.
Syntax
js
toTemporalInstant()
Parameters
None.
Return value
A new Temporal.Instant
object with the same epochMilliseconds
value as this date's timestamp. Its microsecond and nanosecond components are always 0
.
Exceptions
RangeError
-
Thrown if the date is invalid (it has a timestamp of
NaN
).
Examples
Using toTemporalInstant()
js
const legacyDate = new Date("2021-07-01T12:34:56.789Z");
const instant = legacyDate.toTemporalInstant();
// Further convert it to other objects
const zdt = instant.toZonedDateTimeISO("UTC");
const date = zdt.toPlainDate();
console.log(date.toString()); // 2021-07-01
Specifications
| Specification |
|---|
| Temporal # sec-date.prototype.totemporalinstant |


Date.prototype.toLocaleTimeString()

Date.prototype.toLocaleTimeString()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The toLocaleTimeString()
method of Date
instances returns a string with a language-sensitive representation of the time portion of this date in the local timezone. In implementations with Intl.DateTimeFormat
API support, this method delegates to Intl.DateTimeFormat
.
Every time toLocaleTimeString
is called, it has to perform a search in a big database of localization strings, which is potentially inefficient. When the method is called many times with the same arguments, it is better to create an Intl.DateTimeFormat
object and use its format()
method, because a DateTimeFormat
object remembers the arguments passed to it and may decide to cache a slice of the database, so future format
calls can search for localization strings within a more constrained context.
Try it
// Depending on timezone, your results will vary
const event = new Date("August 19, 1975 23:15:30 GMT+00:00");
console.log(event.toLocaleTimeString("en-US"));
// Expected output: "1:15:30 AM"
console.log(event.toLocaleTimeString("it-IT"));
// Expected output: "01:15:30"
console.log(event.toLocaleTimeString("ar-EG"));
// Expected output: "١٢:١٥:٣٠ ص"
Syntax
toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)
Parameters
The locales
and options
parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.
In implementations that support the Intl.DateTimeFormat
API, these parameters correspond exactly to the Intl.DateTimeFormat()
constructor's parameters. Implementations without Intl.DateTimeFormat
support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.
locales
Optional-
A string with a BCP 47 language tag, or an array of such strings. Corresponds to the
locales
parameter of theIntl.DateTimeFormat()
constructor.In implementations without
Intl.DateTimeFormat
support, this parameter is ignored and the host's locale is usually used. options
Optional-
An object adjusting the output format. Corresponds to the
options
parameter of theIntl.DateTimeFormat()
constructor. IfdayPeriod
,hour
,minute
,second
, andfractionalSecondDigits
are all undefined, thenhour
,minute
,second
will be set to"numeric"
.In implementations without
Intl.DateTimeFormat
support, this parameter is ignored.
See the Intl.DateTimeFormat()
constructor for details on these parameters and how to use them.
Return value
A string representing the time portion of the given date according to language-specific conventions.
In implementations with Intl.DateTimeFormat
, this is equivalent to new Intl.DateTimeFormat(locales, options).format(date)
, where options
has been normalized as described above.
Note:
Most of the time, the formatting returned by toLocaleTimeString()
is consistent. However, the output may vary between implementations, even within the same locale — output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should not compare the results of toLocaleTimeString()
to hardcoded constants.
Examples
Using toLocaleTimeString()
Basic use of this method without specifying a locale
returns a formatted string in the default locale and with default options.
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
// toLocaleTimeString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleTimeString());
// "7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles
Checking for support for locales and options parameters
The locales
and options
parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, toLocaleTimeString()
always uses the system's locale, which may not be what you want. Because any implementation that supports the locales
and options
parameters must support the Intl
API, you can check the existence of the latter for support:
function toLocaleTimeStringSupportsLocales() {
return (
typeof Intl === "object" &&
!!Intl &&
typeof Intl.DateTimeFormat === "function"
);
}
Using locales
This example shows some of the variations in localized time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales
argument:
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// formats below assume the local time zone of the locale;
// America/Los_Angeles for the US
// US English uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString("en-US"));
// "7:00:00 PM"
// British English uses 24-hour time without AM/PM
console.log(date.toLocaleTimeString("en-GB"));
// "03:00:00"
// Korean uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString("ko-KR"));
// "오후 12:00:00"
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleTimeString("ar-EG"));
// "٧:٠٠:٠٠ م"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(date.toLocaleTimeString(["ban", "id"]));
// "11.00.00"
Using options
The results provided by toLocaleTimeString()
can be customized using the options
parameter:
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// An application may want to use UTC and make that visible
const options = { timeZone: "UTC", timeZoneName: "short" };
console.log(date.toLocaleTimeString("en-US", options));
// "3:00:00 AM GMT"
// Sometimes even the US needs 24-hour time
console.log(date.toLocaleTimeString("en-US", { hour12: false }));
// "19:00:00"
// Show only hours and minutes, use options with the default locale - use an empty array
console.log(
date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
);
// "20:01"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-date.prototype.tolocaletimestring |
| ECMAScript® 2026 Internationalization API Specification # sup-date.prototype.tolocaletimestring |


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/bigint/tolocalestring/index.md

# Original Wiki contributors
wbamberg
fscholz
chrisdavidmills


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/symbol/description/index.md

# Original Wiki contributors
wbamberg
fscholz
ddbeck
sideshowbarker
ExE-Boss
turtlemaster19
LJHarb


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/array/symbol.unscopables/index.md

# Original Wiki contributors
mfuji09
wbamberg
fscholz
RainSlide
nmve
kdex
matt-tingen
evilpie


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/bigint/asuintn/index.md

# Original Wiki contributors
fscholz
mfuji09
wbamberg
AnyhowStep
sideshowbarker
ExE-Boss


Intl.DateTimeFormat

Intl.DateTimeFormat
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The Intl.DateTimeFormat
object enables language-sensitive date and time formatting.
Try it
const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
// Results below assume UTC timezone - your results may vary
// Specify default date formatting for language (locale)
console.log(new Intl.DateTimeFormat("en-US").format(date));
// Expected output: "12/20/2020"
// Specify default date formatting for language with a fallback language (in this case Indonesian)
console.log(new Intl.DateTimeFormat(["ban", "id"]).format(date));
// Expected output: "20/12/2020"
// Specify date and time format using "style" options (i.e. full, long, medium, short)
console.log(
new Intl.DateTimeFormat("en-GB", {
dateStyle: "full",
timeStyle: "long",
timeZone: "Australia/Sydney",
}).format(date),
);
// Expected output: "Sunday, 20 December 2020 at 14:23:16 GMT+11"
Constructor
Intl.DateTimeFormat()
-
Creates a new
Intl.DateTimeFormat
object.
Static methods
Intl.DateTimeFormat.supportedLocalesOf()
-
Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance properties
These properties are defined on Intl.DateTimeFormat.prototype
and shared by all Intl.DateTimeFormat
instances.
Intl.DateTimeFormat.prototype.constructor
-
The constructor function that created the instance object. For
Intl.DateTimeFormat
instances, the initial value is theIntl.DateTimeFormat
constructor. Intl.DateTimeFormat.prototype[Symbol.toStringTag]
-
The initial value of the
[Symbol.toStringTag]
property is the string"Intl.DateTimeFormat"
. This property is used inObject.prototype.toString()
.
Instance methods
Intl.DateTimeFormat.prototype.format()
-
Getter function that formats a date according to the locale and formatting options of this
DateTimeFormat
object. Intl.DateTimeFormat.prototype.formatRange()
-
This method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating
DateTimeFormat
. Intl.DateTimeFormat.prototype.formatRangeToParts()
-
This method receives two Dates and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.
Intl.DateTimeFormat.prototype.formatToParts()
-
Returns an
Array
of objects representing the date string in parts that can be used for custom locale-aware formatting. Intl.DateTimeFormat.prototype.resolvedOptions()
-
Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
Examples
Using DateTimeFormat
In basic use without specifying a locale, DateTimeFormat
uses the default locale and default options.
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// toLocaleString without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// "12/19/2012" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)
Using locales
This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales
argument:
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time)
// US English uses month-day-year order
console.log(new Intl.DateTimeFormat("en-US").format(date));
// "12/19/2012"
// British English uses day-month-year order
console.log(new Intl.DateTimeFormat("en-GB").format(date));
// "19/12/2012"
// Korean uses year-month-day order
console.log(new Intl.DateTimeFormat("ko-KR").format(date));
// "2012. 12. 19."
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.DateTimeFormat("ar-EG").format(date));
// "١٩/١٢/٢٠١٢"
// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(new Intl.DateTimeFormat("ja-JP-u-ca-japanese").format(date));
// "24/12/19"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(new Intl.DateTimeFormat(["ban", "id"]).format(date));
// "19/12/2012"
Using options
The date and time formats can be customized using the options
argument:
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));
// request a weekday along with a long date
let options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
console.log(new Intl.DateTimeFormat("de-DE", options).format(date));
// "Donnerstag, 20. Dezember 2012"
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// "Thursday, December 20, 2012, GMT"
// sometimes you want to be more precise
options = {
hour: "numeric",
minute: "numeric",
second: "numeric",
timeZone: "Australia/Sydney",
timeZoneName: "short",
};
console.log(new Intl.DateTimeFormat("en-AU", options).format(date));
// "2:00:00 pm AEDT"
// sometimes you want to be very precise
options.fractionalSecondDigits = 3; // number digits for fraction-of-seconds
console.log(new Intl.DateTimeFormat("en-AU", options).format(date));
// "2:00:00.200 pm AEDT"
// sometimes even the US needs 24-hour time
options = {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false,
timeZone: "America/Los_Angeles",
};
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// "12/19/2012, 19:00:00"
// to specify options but use the browser's default locale, use undefined
console.log(new Intl.DateTimeFormat(undefined, options).format(date));
// "12/19/2012, 19:00:00"
// sometimes it's helpful to include the period of the day
options = { hour: "numeric", dayPeriod: "short" };
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// 10 at night
The used calendar and numbering formats can also be set independently via options
arguments:
const options = { calendar: "chinese", numberingSystem: "arab" };
const dateFormat = new Intl.DateTimeFormat(undefined, options);
const usedOptions = dateFormat.resolvedOptions();
console.log(usedOptions.calendar);
// "chinese"
console.log(usedOptions.numberingSystem);
// "arab"
console.log(usedOptions.timeZone);
// "America/New_York" (the users default timezone)
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # datetimeformat-objects |
Browser compatibility
See also
- Polyfill of
Intl.DateTimeFormat
in FormatJS Intl
Date.prototype.toLocaleString()
Date.prototype.toLocaleDateString()
Date.prototype.toLocaleTimeString()
Temporal.Instant.prototype.toLocaleString()
Temporal.PlainDate.prototype.toLocaleString()
Temporal.PlainDateTime.prototype.toLocaleString()
Temporal.PlainTime.prototype.toLocaleString()
Temporal.PlainYearMonth.prototype.toLocaleString()
Temporal.PlainMonthDay.prototype.toLocaleString()
Temporal.ZonedDateTime.prototype.toLocaleString()


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/number/valueof/index.md

# Original Wiki contributors
mfuji09
fscholz
Zearin_Galaurum
alattalatta
wbamberg
jameshkramer
eduardoboucas
ziyunfei
Mingun
ethertank
Sheppy
evilpie
Waldo
Potappo
Mgjbot


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/number/positive_infinity/index.md

# Original Wiki contributors
mfuji09
fscholz
alattalatta
wbamberg
doubleOrt
jameshkramer
Mingun
AlexChao
Sheppy
evilpie
Sevenspade
Diablownik
Mgjbot
Potappo
Ptak82


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/number/negative_infinity/index.md

# Original Wiki contributors
mfuji09
fscholz
rwaldron
alattalatta
wbamberg
doubleOrt
weblzf
jameshkramer
imagineer-aman
Mingun
AlexChao
Sheppy
ethertank
evilpie
Sevenspade
Mgjbot
Ptak82


Intl.NumberFormat() constructor

Intl.NumberFormat() constructor
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The Intl.NumberFormat()
constructor creates Intl.NumberFormat
objects.
Try it
const number = 123456.789;
console.log(
new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(
number,
),
);
// Expected output: "123.456,79 €"
// The Japanese yen doesn't use a minor unit
console.log(
new Intl.NumberFormat("ja-JP", { style: "currency", currency: "JPY" }).format(
number,
),
);
// Expected output: "￥123,457"
// Limit to three significant digits
console.log(
new Intl.NumberFormat("en-IN", { maximumSignificantDigits: 3 }).format(
number,
),
);
// Expected output: "1,23,000"
Syntax
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. The runtime's default locale is used whenundefined
is passed or when none of the specified locale identifiers is supported. For the general form and interpretation of thelocales
argument, see the parameter description on theIntl
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, theoptions
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, seeIntl.supportedValuesOf()
; the default is locale dependent. This option can also be set through thenu
Unicode extension key; if both are provided, thisoptions
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 — seeIntl.supportedValuesOf()
. There is no default value; if thestyle
is"currency"
, thecurrency
property must be provided. It is normalized to uppercase. 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 listed inIntl.supportedValuesOf()
. Pairs of simple units can be concatenated with "-per-" to make a compound unit. There is no default value; if thestyle
is"unit"
, theunit
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
to21
; the default is1
. minimumFractionDigits
-
The minimum number of fraction digits to use. Possible values are from
0
to100
; the default for plain number and percent formatting is0
; 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). See SignificantDigits/FractionDigits default values for when this default gets applied. maximumFractionDigits
-
The maximum number of fraction digits to use. Possible values are from
0
to100
; the default for plain number formatting is the larger ofminimumFractionDigits
and3
; the default for currency formatting is the larger ofminimumFractionDigits
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 ofminimumFractionDigits
and 0. See SignificantDigits/FractionDigits default values for when this default gets applied. minimumSignificantDigits
-
The minimum number of significant digits to use. Possible values are from
1
to21
; the default is1
. See SignificantDigits/FractionDigits default values for when this default gets applied. maximumSignificantDigits
-
The maximum number of significant digits to use. Possible values are from
1
to21
; the default is21
. See SignificantDigits/FractionDigits default values for when this default gets applied. 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.
The value
"auto"
is normalized to"morePrecision"
ifnotation
is"compact"
and none of the four "FractionDigits"/"SignificantDigits" options are set.Note that for values other than
auto
the result with more precision is calculated from themaximumSignificantDigits
andmaximumFractionDigits
(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
, and5000
; the default is1
. It cannot be mixed with significant-digits rounding or any setting ofroundingPriority
other thanauto
. 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
andminimumSignificantDigits
. "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.
SignificantDigits/FractionDigits default values
For the four options above (the FractionDigits
and SignificantDigits
options), we mentioned their defaults; however, these defaults are not unconditionally applied. They are only applied when the property is actually going to be used, which depends on the roundingPriority
and notation
settings. Specifically:
- If
roundingPriority
is not"auto"
, then all four options apply. - If
roundingPriority
is"auto"
and at least oneSignificantDigits
option is set, then theSignificantDigits
options apply and theFractionDigits
options are ignored. - If
roundingPriority
is"auto"
, and either at least oneFractionDigits
option is set ornotation
is not"compact"
, then theFractionDigits
options apply and theSignificantDigits
options are ignored. - If
roundingPriority
is"auto"
,notation
is"compact"
, and none of the four options are set, then they are set to{ minimumFractionDigits: 0, maximumFractionDigits: 0, minimumSignificantDigits: 1, maximumSignificantDigits: 2 }
, regardless of the defaults mentioned above, androundingPriority
is set to"morePrecision"
.
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"
ifnotation
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).
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
andminimumFractionDigits
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.
- A property that takes enumerated values (such as
TypeError
-
Thrown if the
options.style
property is set to "unit" or "currency", and no value has been set for the corresponding propertyoptions.unit
oroptions.currency
.
Examples
Basic usage
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
const amount = 3500;
console.log(new Intl.NumberFormat().format(amount));
// '3,500' if in US English locale
Decimal and percent formatting
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.
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.
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:
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:
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:
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:
// 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
):
// 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:
// 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.
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.
// 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.
// 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 21 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
.
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.
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:
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:
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:
// 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):
// 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:
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
.
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 10,
});
console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.30"
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).
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® 2026 Internationalization API Specification # sec-intl-numberformat-constructor |


String: length

String: length
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The length
data property of a String
value contains the length of the string in UTF-16 code units.
Try it
const str = "Life, the universe and everything. Answer:";
console.log(`${str} ${str.length}`);
// Expected output: "Life, the universe and everything. Answer: 42"
Value
A non-negative integer.
Property attributes of String: length | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
Description
This property returns the number of code units in the string. JavaScript uses UTF-16 encoding, where each Unicode character may be encoded as one or two code units, so it's possible for the value returned by length
to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, mathematical symbols, or obscure Chinese characters, you may need to account for the difference between code units and characters.
The language specification requires strings to have a maximum length of 253 - 1 elements, which is the upper limit for precise integers. However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device's memory, so implementations tend to lower the threshold, which allows the string's length to be conveniently stored in a 32-bit integer.
- In V8 (used by Chrome and Node), the maximum length is 229 - 24 (~1GiB). On 32-bit systems, the maximum length is 228 - 16 (~512MiB).
- In Firefox, the maximum length is 230 - 2 (~2GiB). Before Firefox 65, the maximum length was 228 - 1 (~512MiB).
- In Safari, the maximum length is 231 - 1 (~4GiB).
If you are working with large strings in other encodings (such as UTF-8 files or blobs), note that when you load the data into a JS string, the encoding always becomes UTF-16. The size of the string may be different from the size of the source file.
const str1 = "a".repeat(2 ** 29 - 24); // Success
const str2 = "a".repeat(2 ** 29 - 23); // RangeError: Invalid string length
const buffer = new Uint8Array(2 ** 29 - 24).fill("a".codePointAt(0)); // This buffer is 512MiB in size
const str = new TextDecoder().decode(buffer); // This string is 1GiB in size
For an empty string, length
is 0.
The static property String.length
is unrelated to the length of strings. It's the arity of the String
function (loosely, the number of formal parameters it has), which is 1.
Since length
counts code units instead of characters, if you want to get the number of characters, you can first split the string with its iterator, which iterates by characters:
function getCharacterLength(str) {
// The string iterator that is used here iterates over characters,
// not mere code units
return [...str].length;
}
console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3
If you want to count characters by grapheme clusters, use Intl.Segmenter
. You can first pass the string you want to split to the segment()
method, and then iterate over the returned Segments
object to get the length:
function getGraphemeCount(str) {
const segmenter = new Intl.Segmenter("en-US", { granularity: "grapheme" });
// The Segments object iterator that is used here iterates over characters in grapheme clusters,
// which may consist of multiple Unicode characters
return [...segmenter.segment(str)].length;
}
console.log(getGraphemeCount("👨👩👧👧")); // 1
Examples
Basic usage
const x = "Mozilla";
const empty = "";
console.log(`${x} is ${x.length} code units long`);
// Mozilla is 7 code units long
console.log(`The empty string has a length of ${empty.length}`);
// The empty string has a length of 0
Strings with length not equal to the number of characters
const emoji = "😄";
console.log(emoji.length); // 2
console.log([...emoji].length); // 1
const adlam = "𞤲𞥋𞤣𞤫";
console.log(adlam.length); // 8
console.log([...adlam].length); // 4
const formula = "∀𝑥∈ℝ,𝑥²≥0";
console.log(formula.length); // 11
console.log([...formula].length); // 9
Assigning to length
Because string is a primitive, attempting to assign a value to a string's length
property has no observable effect, and will throw in strict mode.
const myString = "bluebells";
myString.length = 4;
console.log(myString); // "bluebells"
console.log(myString.length); // 9
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-properties-of-string-instances-length |


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/date/symbol.toprimitive/index.md

# Original Wiki contributors
mfuji09
chrisdavidmills
fscholz
SphinxKnight
wuqiu
Delapouite
eduardoboucas
arai


String.prototype.valueOf()

String.prototype.valueOf()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The valueOf()
method of String
values returns this string value.
Try it
const stringObj = new String("foo");
console.log(stringObj);
// Expected output: String { "foo" }
console.log(stringObj.valueOf());
// Expected output: "foo"
Syntax
js
valueOf()
Parameters
None.
Return value
A string representing the primitive value of a given String
object.
Description
The valueOf()
method of String
returns the primitive value
of a String
object as a string data type. This value is equivalent to
String.prototype.toString()
.
This method is usually called internally by JavaScript and not explicitly in code.
Examples
Using valueOf()
js
const x = new String("Hello world");
console.log(x.valueOf()); // 'Hello world'
Specifications
| Specification |
|---|
| ECMAScript® 2026 Language Specification # sec-string.prototype.valueof |


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/number/nan/index.md

# Original Wiki contributors
mfuji09
chrisdavidmills
fscholz
wbamberg
jameshkramer
Mingun
Sheppy
slippyd
dbruant
evilpie
Mgjbot
Sevenspade
Diablownik
Maian
Nickolay
Dria


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/number/min_value/index.md

# Original Wiki contributors
mfuji09
velusgautam
fscholz
wbamberg
jameshkramer
Mingun
Sheppy
ethertank
ShimShamSam
evilpie
Sevenspade
Mgjbot
Ptak82
Maian
Dria


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/date/valueof/index.md

# Original Wiki contributors
mfuji09
fscholz
schalkneethling
jameshkramer
eduardoboucas
Mingun
ethertank
Sheppy
evilpie
Ptak82
Maian
Dria


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/date/totimestring/index.md

# Original Wiki contributors
mfuji09
Robg1
wbamberg
fscholz
r-i-c-h
schalkneethling
jameshkramer
schlagi123
eduardoboucas
Mingun
kscarfone
Sheppy
ethertank
dtjm
evilpie
Dikrib
Sevenspade


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/date/totemporalinstant/index.md


# Contributors by commit history
https://github.com/mdn/content/commits/main/files/en-us/web/javascript/reference/global_objects/date/tolocaletimestring/index.md

# Original Wiki contributors
mfuji09
chrisbruford
wbamberg
fscholz
sideshowbarker
mika76
leothorp
SphinxKnight
Robg1
schalkneethling
jameshkramer
thetalecrafter
eduardoboucas
Mingun
Norbert
Sheppy
ethertank
evilpie
pwalton
Dikrib
Bold
Ptak82
Maian
Dria


Intl.DateTimeFormat() constructor

Intl.DateTimeFormat() constructor
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The Intl.DateTimeFormat()
constructor creates Intl.DateTimeFormat
objects.
Try it
const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
// Results below assume UTC timezone - your results may vary
// Specify default date formatting for language (locale)
console.log(new Intl.DateTimeFormat("en-US").format(date));
// Expected output: "12/20/2020"
// Specify default date formatting for language with a fallback language (in this case Indonesian)
console.log(new Intl.DateTimeFormat(["ban", "id"]).format(date));
// Expected output: "20/12/2020"
// Specify date and time format using "style" options (i.e. full, long, medium, short)
console.log(
new Intl.DateTimeFormat("en-GB", {
dateStyle: "full",
timeStyle: "long",
timeZone: "Australia/Sydney",
}).format(date),
);
// Expected output: "Sunday, 20 December 2020 at 14:23:16 GMT+11"
Syntax
new Intl.DateTimeFormat()
new Intl.DateTimeFormat(locales)
new Intl.DateTimeFormat(locales, options)
Intl.DateTimeFormat()
Intl.DateTimeFormat(locales)
Intl.DateTimeFormat(locales, options)
Note:
Intl.DateTimeFormat()
can be called with or without new
. Both create a new Intl.DateTimeFormat
instance. However, there's a special behavior when it's called without new
and the this
value is another Intl.DateTimeFormat
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. The runtime's default locale is used whenundefined
is passed or when none of the specified locale identifiers is supported. For the general form and interpretation of thelocales
argument, see the parameter description on theIntl
main page.The following Unicode extension keys are allowed:
These keys can also be set with
options
(as listed below). When both are set, theoptions
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, date-time component options, and style shortcuts.
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. calendar
-
The calendar to use, such as
"chinese"
,"gregory"
,"persian"
, and so on. For a list of supported calendar types, seeIntl.supportedValuesOf()
; the default is locale dependent. This option can also be set through theca
Unicode extension key; if both are provided, thisoptions
property takes precedence. 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, seeIntl.supportedValuesOf()
; the default is locale dependent. This option can also be set through thenu
Unicode extension key; if both are provided, thisoptions
property takes precedence. hour12
-
Whether to use 12-hour time (as opposed to 24-hour time). Possible values are
true
andfalse
; the default is locale dependent. Whentrue
, this option setshourCycle
to either"h11"
or"h12"
, depending on the locale. Whenfalse
, it setshourCycle
to"h23"
.hour12
overrides both thehc
locale extension tag and thehourCycle
option, should either or both of those be present. hourCycle
-
The hour cycle to use. Possible values are
"h11"
,"h12"
,"h23"
, and"h24"
; the default is inferred fromhour12
and locale. This option can also be set through thehc
Unicode extension key; if both are provided, thisoptions
property takes precedence. timeZone
-
The time zone to use. Can be any IANA time zone name, including named identifiers such as
"UTC"
,"America/New_York"
, and"Etc/GMT+8"
, and offset identifiers such as"+01:00"
,"-2359"
, and"+23"
. The default is the runtime's time zone, the same time zone used byDate.prototype.toString()
.
Date-time component options
weekday
-
The representation of the weekday. Possible values are:
era
-
The representation of the era. Possible values are:
year
-
The representation of the year. Possible values are
"numeric"
and"2-digit"
. month
-
The representation of the month. Possible values are:
day
-
The representation of the day. Possible values are
"numeric"
and"2-digit"
. dayPeriod
-
The formatting style used for day periods like "in the morning", "am", "noon", "n" etc. Possible values are
"narrow"
,"short"
, and"long"
.Note: This option only has an effect if a 12-hour clock (
hourCycle: "h12"
orhourCycle: "h11"
) is used. Many locales use the same string irrespective of the width specified. hour
-
The representation of the hour. Possible values are
"numeric"
and"2-digit"
. minute
-
The representation of the minute. Possible values are
"numeric"
and"2-digit"
. second
-
The representation of the second. Possible values are
"numeric"
and"2-digit"
. fractionalSecondDigits
-
The number of digits used to represent fractions of a second (any additional digits are truncated). Possible values are from
1
to3
. timeZoneName
-
The localized representation of the time zone name. Possible values are:
"long"
-
Long localized form (e.g.,
Pacific Standard Time
,Nordamerikanische Westküsten-Normalzeit
) "short"
-
Short localized form (e.g.:
PST
,GMT-8
) "shortOffset"
-
Short localized GMT format (e.g.,
GMT-8
) "longOffset"
-
Long localized GMT format (e.g.,
GMT-08:00
) "shortGeneric"
-
Short generic non-location format (e.g.:
PT
,Los Angeles Zeit
). "longGeneric"
-
Long generic non-location format (e.g.:
Pacific Time
,Nordamerikanische Westküstenzeit
)
Note: Timezone display may fall back to another format if a required string is unavailable. For example, the non-location formats should display the timezone without a specific country/city location like "Pacific Time", but may fall back to a timezone like "Los Angeles Time".
Date-time component default values
If any of the date-time component options are specified, then dateStyle
and timeStyle
must be undefined
. If all date-time component options and dateStyle
/timeStyle
are undefined
, some default options for date-time components are set, which depend on the object that the formatting method was called with:
- When formatting
Temporal.PlainDate
andDate
,year
,month
, andday
default to"numeric"
. - When formatting
Temporal.PlainTime
,hour
,minute
, andsecond
default to"numeric"
. - When formatting
Temporal.PlainYearMonth
,year
andmonth
default to"numeric"
. - When formatting
Temporal.PlainMonthDay
,month
andday
default to"numeric"
. - When formatting
Temporal.PlainDateTime
andTemporal.Instant
,year
,month
,day
,hour
,minute
, andsecond
default to"numeric"
.
Format matching
Implementations are required to support displaying at least the following subsets of date-time components:
weekday
,year
,month
,day
,hour
,minute
,second
weekday
,year
,month
,day
year
,month
,day
year
,month
month
,day
hour
,minute
,second
hour
,minute
The date-time component styles requested might not directly correspond to a valid format supported by the locale, so the format matcher allows you to specify how to match the requested styles to the closest supported format.
formatMatcher
-
The format matching algorithm to use. Possible values are
"basic"
and"best fit"
; the default is"best fit"
. The algorithm for"best fit"
is implementation-defined, and"basic"
is defined by the spec. This option is only used when bothdateStyle
andtimeStyle
areundefined
(so that each date-time component's format is individually customizable).
Style shortcuts
dateStyle
-
The date formatting style to use. Possible values are
"full"
,"long"
,"medium"
, and"short"
. It expands to styles forweekday
,day
,month
,year
, andera
, with the exact combination of values depending on the locale. When formatting objects such asTemporal.PlainDate
,Temporal.PlainYearMonth
, andTemporal.PlainMonthDay
,dateStyle
will resolve to only those fields relevant to the object. timeStyle
-
The time formatting style to use. Possible values are
"full"
,"long"
,"medium"
, and"short"
. It expands to styles forhour
,minute
,second
, andtimeZoneName
, with the exact combination of values depending on the locale.
Note:
dateStyle
and timeStyle
can be used with each other, but not with other date-time component options (e.g., weekday
, hour
, month
, etc.).
You can format different object types depending on which of the style shortcut options you include:
- If the
dateStyle
is specified, then you can formatTemporal.PlainDate
,Temporal.PlainYearMonth
, andTemporal.PlainMonthDay
objects. - If the
timeStyle
is specified, then you can formatTemporal.PlainTime
objects. - If either
dateStyle
ortimeStyle
is specified, then you can formatTemporal.PlainDateTime
andDate
objects.
Return value
A new Intl.DateTimeFormat
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.DateTimeFormat()
can be called with or without new
, and a new Intl.DateTimeFormat
instance is returned in both cases. However, if the this
value is an object that is instanceof
Intl.DateTimeFormat
(doesn't necessarily mean it's created via new Intl.DateTimeFormat
; just that it has Intl.DateTimeFormat.prototype
in its prototype chain), then the value of this
is returned instead, with the newly created Intl.DateTimeFormat
object hidden in a [Symbol(IntlLegacyConstructedSymbol)]
property (a unique symbol that's reused between instances).
const formatter = Intl.DateTimeFormat.call(
{ __proto__: Intl.DateTimeFormat.prototype },
"en-US",
{ dateStyle: "full" },
);
console.log(Object.getOwnPropertyDescriptors(formatter));
// {
// [Symbol(IntlLegacyConstructedSymbol)]: {
// value: DateTimeFormat [Intl.DateTimeFormat] {},
// writable: false,
// enumerable: false,
// configurable: false
// }
// }
Note that there's only one actual Intl.DateTimeFormat
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: "TypeError: formatRange method called on incompatible Object", because those methods don't consult the hidden instance's options.
This behavior, called ChainDateTimeFormat
, does not happen when Intl.DateTimeFormat()
is called without new
but with this
set to anything else that's not an instanceof Intl.DateTimeFormat
. If you call it directly as Intl.DateTimeFormat()
, the this
value is Intl
, and a new Intl.DateTimeFormat
instance is created normally.
Exceptions
RangeError
-
Thrown if
locales
oroptions
contain invalid values.
Examples
Using DateTimeFormat
In basic use without specifying a locale, DateTimeFormat
uses the default
locale and default options.
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// toLocaleString without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// "12/19/2012" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)
Using timeStyle and dateStyle
dateStyle
and timeStyle
provide a shortcut for setting multiple date-time component options at once. For example, for en-US
, dateStyle: "short"
is equivalent to setting year: "2-digit", month: "numeric", day: "numeric"
, and timeStyle: "short"
is equivalent to setting hour: "numeric", minute: "numeric"
.
const shortTime = new Intl.DateTimeFormat("en-US", {
timeStyle: "short",
});
console.log(shortTime.format(Date.now())); // "1:31 PM"
const shortDate = new Intl.DateTimeFormat("en-US", {
dateStyle: "short",
});
console.log(shortDate.format(Date.now())); // "7/7/20"
const mediumTime = new Intl.DateTimeFormat("en-US", {
timeStyle: "medium",
dateStyle: "short",
});
console.log(mediumTime.format(Date.now())); // "7/7/20, 1:31:55 PM"
However, the exact (locale dependent) component styles they resolve to are not included in the resolved options. This ensures the result of resolvedOptions()
can be passed directly to the Intl.DateTimeFormat()
constructor (because an options
object with both dateStyle
or timeStyle
and individual date or time component styles is not valid).
console.log(shortDate.resolvedOptions().year); // undefined
Using dayPeriod
Use the dayPeriod
option to output a string for the times of day ("in the morning", "at night", "noon", etc.). Note, that this only works when formatting for a 12 hour clock (hourCycle: 'h12'
or hourCycle: 'h11'
) and that for many locales the strings are the same irrespective of the value passed for the dayPeriod
.
const date = Date.UTC(2012, 11, 17, 4, 0, 42);
console.log(
new Intl.DateTimeFormat("en-GB", {
hour: "numeric",
hourCycle: "h12",
dayPeriod: "short",
timeZone: "UTC",
}).format(date),
);
// 4 at night" (same formatting in en-GB for all dayPeriod values)
console.log(
new Intl.DateTimeFormat("fr", {
hour: "numeric",
hourCycle: "h12",
dayPeriod: "narrow",
timeZone: "UTC",
}).format(date),
);
// "4 mat." (same output in French for both narrow/short dayPeriod)
console.log(
new Intl.DateTimeFormat("fr", {
hour: "numeric",
hourCycle: "h12",
dayPeriod: "long",
timeZone: "UTC",
}).format(date),
);
// "4 du matin"
Using timeZoneName
Use the timeZoneName
option to output a string for the timezone ("GMT", "Pacific Time", etc.).
const date = Date.UTC(2021, 11, 17, 3, 0, 42);
const timezoneNames = [
"short",
"long",
"shortOffset",
"longOffset",
"shortGeneric",
"longGeneric",
];
for (const zoneName of timezoneNames) {
// Do something with currentValue
const formatter = new Intl.DateTimeFormat("en-US", {
timeZone: "America/Los_Angeles",
timeZoneName: zoneName,
});
console.log(`${zoneName}: ${formatter.format(date)}`);
}
// Logs:
// short: 12/16/2021, PST
// long: 12/16/2021, Pacific Standard Time
// shortOffset: 12/16/2021, GMT-8
// longOffset: 12/16/2021, GMT-08:00
// shortGeneric: 12/16/2021, PT
// longGeneric: 12/16/2021, Pacific Time
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-intl-datetimeformat-constructor |


Intl.DateTimeFormat.prototype.format()

Intl.DateTimeFormat.prototype.format()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2017.
The format()
method of Intl.DateTimeFormat
instances formats a date according to the locale and formatting options of this Intl.DateTimeFormat
object.
Try it
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
const date = new Date(2012, 5);
const dateTimeFormat1 = new Intl.DateTimeFormat("sr-RS", options);
console.log(dateTimeFormat1.format(date));
// Expected output: "петак, 1. јун 2012."
const dateTimeFormat2 = new Intl.DateTimeFormat("en-GB", options);
console.log(dateTimeFormat2.format(date));
// Expected output: "Friday, 1 June 2012"
const dateTimeFormat3 = new Intl.DateTimeFormat("en-US", options);
console.log(dateTimeFormat3.format(date));
// Expected output: "Friday, June 1, 2012"
Syntax
format(date)
Parameters
date
-
The date to format. Can be a
Date
orTemporal.PlainDateTime
object. Additionally can be aTemporal.PlainTime
,Temporal.PlainDate
,Temporal.PlainYearMonth
, orTemporal.PlainMonthDay
object if theDateTimeFormat
object was configured to print at least one relevant part of the date.Note: A
Temporal.ZonedDateTime
object will always throw aTypeError
; useTemporal.ZonedDateTime.prototype.toLocaleString()
or convert it to aTemporal.PlainDateTime
object instead.Omitting it results in formatting the current date (as returned by
Date.now()
), which could be slightly confusing, so it is advisable to always explicitly pass a date.
Return value
A string representing the given date
formatted according to the locale and formatting options of this Intl.DateTimeFormat
object.
Note:
Most of the time, the formatting returned by format()
is consistent. However, the output may vary between implementations, even within the same locale — output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should not compare the results of format()
to hardcoded constants.
Examples
Using format
Use the format
getter function for formatting a single date, here for
Serbia:
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
const dateTimeFormat = new Intl.DateTimeFormat("sr-RS", options);
console.log(dateTimeFormat.format(new Date()));
// "недеља, 7. април 2013."
Using format with map
Use the format
getter function for formatting all dates in an array. Note
that the function is bound to the Intl.DateTimeFormat
from which it was obtained, so it can be passed directly to
Array.prototype.map()
.
const a = [new Date(2012, 8), new Date(2012, 11), new Date(2012, 3)];
const options = { year: "numeric", month: "long" };
const dateTimeFormat = new Intl.DateTimeFormat("pt-BR", options);
const formatted = a.map(dateTimeFormat.format);
console.log(formatted.join("; "));
// "setembro de 2012; dezembro de 2012; abril de 2012"
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # sec-intl.datetimeformat.prototype.format |


Temporal.Instant.fromEpochMilliseconds()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
The Temporal.Instant.fromEpochMilliseconds()
static method creates a new Temporal.Instant
object from the number of milliseconds since the Unix epoch (midnight at the beginning of January 1, 1970, UTC).
To convert a Date
object to a Temporal.Instant
object, use Date.prototype.toTemporalInstant()
instead.
Syntax
js
Temporal.Instant.fromEpochMilliseconds(epochMilliseconds)
Parameters
epochMilliseconds
-
A number representing the number of milliseconds since the Unix epoch. Internally, it is converted to a BigInt and multiplied by
1e6
to get the number of nanoseconds.
Return value
A new Temporal.Instant
object representing the instant in time specified by epochMilliseconds
.
Exceptions
RangeError
-
Thrown in one of the following cases:
epochMilliseconds
cannot be converted to a BigInt (e.g., not an integer).epochMilliseconds
is not in the representable range, which is ±108 days, or about ±273,972.6 years, from the Unix epoch.
Examples
Using Temporal.Instant.fromEpochMilliseconds()
js
const instant = Temporal.Instant.fromEpochMilliseconds(0);
console.log(instant.toString()); // 1970-01-01T00:00:00Z
const vostok1Liftoff = Temporal.Instant.fromEpochMilliseconds(-275248380000);
console.log(vostok1Liftoff.toString()); // 1961-04-12T06:07:00Z
const sts1Liftoff = Temporal.Instant.fromEpochMilliseconds(355924804000);
console.log(sts1Liftoff.toString()); // 1981-04-12T12:00:04Z
Specifications
| Specification |
|---|
| Temporal # sec-temporal.instant.fromepochmilliseconds |


Intl.Segmenter

Intl.Segmenter
Baseline
2024
Newly available
Since April 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
The Intl.Segmenter
object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.
Try it
const segmenterFr = new Intl.Segmenter("fr", { granularity: "word" });
const string = "Que ma joie demeure";
const iterator = segmenterFr.segment(string)[Symbol.iterator]();
console.log(iterator.next().value.segment);
// Expected output: 'Que'
console.log(iterator.next().value.segment);
// Expected output: ' '
Constructor
Intl.Segmenter()
-
Creates a new
Intl.Segmenter
object.
Static methods
Intl.Segmenter.supportedLocalesOf()
-
Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance properties
These properties are defined on Intl.Segmenter.prototype
and shared by all Intl.Segmenter
instances.
Intl.Segmenter.prototype.constructor
-
The constructor function that created the instance object. For
Intl.Segmenter
instances, the initial value is theIntl.Segmenter
constructor. Intl.Segmenter.prototype[Symbol.toStringTag]
-
The initial value of the
[Symbol.toStringTag]
property is the string"Intl.Segmenter"
. This property is used inObject.prototype.toString()
.
Instance methods
Intl.Segmenter.prototype.resolvedOptions()
-
Returns a new object with properties reflecting the locale and granularity options computed during initialization of this
Intl.Segmenter
object. Intl.Segmenter.prototype.segment()
-
Returns a new iterable
Segments
instance representing the segments of a string according to the locale and granularity of thisIntl.Segmenter
instance.
Examples
Basic usage and difference from String.prototype.split()
If we were to use String.prototype.split(" ")
to segment a text in words, we would not get the correct result if the locale of the text does not use whitespaces between words (which is the case for Japanese, Chinese, Thai, Lao, Khmer, Myanmar, etc.).
const str = "吾輩は猫である。名前はたぬき。";
console.table(str.split(" "));
// ['吾輩は猫である。名前はたぬき。']
// The two sentences are not correctly segmented.
const str = "吾輩は猫である。名前はたぬき。";
const segmenterJa = new Intl.Segmenter("ja-JP", { granularity: "word" });
const segments = segmenterJa.segment(str);
console.table(Array.from(segments));
// [{segment: '吾輩', index: 0, input: '吾輩は猫である。名前はたぬき。', isWordLike: true},
// etc.
// ]
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # segmenter-objects |


Intl.RelativeTimeFormat

Intl.RelativeTimeFormat
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.
The Intl.RelativeTimeFormat
object enables language-sensitive relative time formatting.
Try it
const rtf1 = new Intl.RelativeTimeFormat("en", { style: "short" });
console.log(rtf1.format(3, "quarter"));
// Expected output: "in 3 qtrs."
console.log(rtf1.format(-1, "day"));
// Expected output: "1 day ago"
const rtf2 = new Intl.RelativeTimeFormat("es", { numeric: "auto" });
console.log(rtf2.format(2, "day"));
// Expected output: "pasado mañana"
Constructor
Intl.RelativeTimeFormat()
-
Creates a new
Intl.RelativeTimeFormat
object.
Static methods
Intl.RelativeTimeFormat.supportedLocalesOf()
-
Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance properties
These properties are defined on Intl.RelativeTimeFormat.prototype
and shared by all Intl.RelativeTimeFormat
instances.
Intl.RelativeTimeFormat.prototype.constructor
-
The constructor function that created the instance object. For
Intl.RelativeTimeFormat
instances, the initial value is theIntl.RelativeTimeFormat
constructor. Intl.RelativeTimeFormat.prototype[Symbol.toStringTag]
-
The initial value of the
[Symbol.toStringTag]
property is the string"Intl.RelativeTimeFormat"
. This property is used inObject.prototype.toString()
.
Instance methods
Intl.RelativeTimeFormat.prototype.format()
-
Formats a
value
and aunit
according to the locale and formatting options of the givenIntl.RelativeTimeFormat
object. Intl.RelativeTimeFormat.prototype.formatToParts()
-
Returns an
Array
of objects representing the relative time format in parts that can be used for custom locale-aware formatting. Intl.RelativeTimeFormat.prototype.resolvedOptions()
-
Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
Examples
Basic format usage
The following example shows how to use a relative time formatter for the English language.
// Create a relative time formatter in your locale
// with default values explicitly passed in.
const rtf = new Intl.RelativeTimeFormat("en", {
localeMatcher: "best fit", // other values: "lookup"
numeric: "always", // other values: "auto"
style: "long", // other values: "short" or "narrow"
});
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "1 day ago"
// Format relative time using positive value (1).
rtf.format(1, "day"); // "in 1 day"
Using formatToParts
The following example shows how to create a relative time formatter returning formatted parts.
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// Format relative time using the day unit.
rtf.formatToParts(-1, "day");
// [{ type: "literal", value: "yesterday"}]
rtf.formatToParts(100, "day");
// [
// { type: "literal", value: "in " },
// { type: "integer", value: "100", unit: "day" },
// { type: "literal", value: " days" }
// ]
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # relativetimeformat-objects |
Browser compatibility
See also
- Polyfill of
Intl.RelativeTimeFormat
in FormatJS Intl
Intl.RelativeTimeFormat
on v8.dev (2018)


Intl.PluralRules

Intl.PluralRules
Baseline
Widely available
*
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2019.
* Some parts of this feature may have varying levels of support.
The Intl.PluralRules
object enables plural-sensitive formatting and plural-related language rules.
Description
Languages use different patterns for expressing both plural numbers of items (cardinal numbers) and for expressing the order of items (ordinal numbers). English has two forms for expressing cardinal numbers: one for the singular "item" (1 hour, 1 dog, 1 fish) and the other for zero or any other number of "items" (0 hours, 2 lemmings, 100000.5 fish), while Chinese has only one form, and Arabic has six! Similarly, English has four forms for expressing ordinal numbers: "th", "st", "nd", "rd", giving the sequence: 0th, 1st, 2nd, 3rd, 4th, 5th, ..., 21st, 22nd, 23rd, 24th, 25th, and so on, while both Chinese and Arabic only have one form for ordinal numbers.
Given a particular language and set of formatting options, the methods Intl.PluralRules.prototype.select()
and Intl.PluralRules.prototype.selectRange()
return a tag that represents the plural form of a single or a range of numbers, cardinal or ordinal.
Code can use the returned tags to represent numbers appropriately for the given language.
The full set of tags that might be returned are: zero
, one
, two
, few
, many
, and other
(the "general" plural form, also used if the language only has one form).
As English only has two forms for cardinal numbers, the select()
method returns only two tags: "one"
for the singular case, and "other"
for all other cardinal numbers.
This allows construction of sentences that make sense in English for each case, such as: "1 dog is happy; do you want to play with it?" and "10 dogs are happy; do you want to play with them?".
Creating appropriate sentences for each form depends on the language, and even in English may not be as simple as just adding "s" to a noun to make the plural form. Using the example above, we see that the form may affect:
- Nouns: 1 dog, 2 dogs (but not "fish" or "sheep", which have the same singular and plural form).
- Verbs: 1 dog is happy, 2 dogs are happy.
- Pronouns (and other referents): Do you want to play with it / them.
Other languages have more forms, and choosing appropriate sentences can be even more complex.
select()
can return any of four tags for ordinal numbers in English, representing each of the allowed forms: one
for "st" numbers (1, 21, 31, ...), two
for "nd" numbers (2, 22, 32, ...), few
for "rd" numbers (3, 33, 43, ...), and other
for "th" numbers (0, 4-20, etc.).
Again, the returned tags allow appropriate formatting of strings describing an ordinal number.
For more information about the rules and how they are used, see Plural Rules. For a list of the rules and how they apply for different languages, see the LDML Language Plural Rules.
Constructor
Intl.PluralRules()
-
Creates a new
Intl.PluralRules
object.
Static methods
Intl.PluralRules.supportedLocalesOf()
-
Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance properties
These properties are defined on Intl.PluralRules.prototype
and shared by all Intl.PluralRules
instances.
Intl.PluralRules.prototype.constructor
-
The constructor function that created the instance object. For
Intl.PluralRules
instances, the initial value is theIntl.PluralRules
constructor. Intl.PluralRules.prototype[Symbol.toStringTag]
-
The initial value of the
[Symbol.toStringTag]
property is the string"Intl.PluralRules"
. This property is used inObject.prototype.toString()
.
Instance methods
Intl.PluralRules.prototype.resolvedOptions()
-
Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
Intl.PluralRules.prototype.select()
-
Returns a string indicating which plural rule to use for locale-aware formatting.
Intl.PluralRules.prototype.selectRange()
-
This method receives two values and returns a string indicating which plural rule to use for locale-aware formatting.
Examples
Using locales
This example shows some of the variations in localized plural rules for cardinal numbers.
In order to get the format for the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the constructor locales
argument:
// US English
const enCardinalRules = new Intl.PluralRules("en-US");
console.log(enCardinalRules.select(0)); // "other"
console.log(enCardinalRules.select(1)); // "one"
console.log(enCardinalRules.select(2)); // "other"
console.log(enCardinalRules.select(3)); // "other"
// Arabic
const arCardinalRules = new Intl.PluralRules("ar-EG");
console.log(arCardinalRules.select(0)); // "zero"
console.log(arCardinalRules.select(1)); // "one"
console.log(arCardinalRules.select(2)); // "two"
console.log(arCardinalRules.select(6)); // "few"
console.log(arCardinalRules.select(18)); // "many"
Using options
The plural form of the specified number may also depend on constructor options
, such as how the number is rounded, and whether it is cardinal or ordinal.
This example shows how you can set the type of rules to "ordinal", and how this affects the form for some numbers in US English.
// US English - ordinal
const enOrdinalRules = new Intl.PluralRules("en-US", { type: "ordinal" });
console.log(enOrdinalRules.select(0)); // "other" (0th)
console.log(enOrdinalRules.select(1)); // "one" (1st)
console.log(enOrdinalRules.select(2)); // "two" (2nd)
console.log(enOrdinalRules.select(3)); // "few" (3rd)
console.log(enOrdinalRules.select(4)); // "other" (4th)
console.log(enOrdinalRules.select(21)); // "one" (21st)
Formatting text using the returned tag
The code below extends the previous example, showing how you might use the returned tag for an ordinal number to format text in English.
const enOrdinalRules = new Intl.PluralRules("en-US", { type: "ordinal" });
const suffixes = new Map([
["one", "st"],
["two", "nd"],
["few", "rd"],
["other", "th"],
]);
const formatOrdinals = (n) => {
const rule = enOrdinalRules.select(n);
const suffix = suffixes.get(rule);
return `${n}${suffix}`;
};
formatOrdinals(0); // '0th'
formatOrdinals(1); // '1st'
formatOrdinals(2); // '2nd'
formatOrdinals(3); // '3rd'
formatOrdinals(4); // '4th'
formatOrdinals(11); // '11th'
formatOrdinals(21); // '21st'
formatOrdinals(42); // '42nd'
formatOrdinals(103); // '103rd'
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # pluralrules-objects |


Intl.ListFormat

Intl.ListFormat
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2021.
The Intl.ListFormat
object enables language-sensitive list formatting.
Try it
const vehicles = ["Motorcycle", "Bus", "Car"];
const formatter = new Intl.ListFormat("en", {
style: "long",
type: "conjunction",
});
console.log(formatter.format(vehicles));
// Expected output: "Motorcycle, Bus, and Car"
const formatter2 = new Intl.ListFormat("de", {
style: "short",
type: "disjunction",
});
console.log(formatter2.format(vehicles));
// Expected output: "Motorcycle, Bus oder Car"
const formatter3 = new Intl.ListFormat("en", { style: "narrow", type: "unit" });
console.log(formatter3.format(vehicles));
// Expected output: "Motorcycle Bus Car"
Constructor
Intl.ListFormat()
-
Creates a new
Intl.ListFormat
object.
Static methods
Intl.ListFormat.supportedLocalesOf()
-
Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Instance properties
These properties are defined on Intl.ListFormat.prototype
and shared by all Intl.ListFormat
instances.
Intl.ListFormat.prototype.constructor
-
The constructor function that created the instance object. For
Intl.ListFormat
instances, the initial value is theIntl.ListFormat
constructor. Intl.ListFormat.prototype[Symbol.toStringTag]
-
The initial value of the
[Symbol.toStringTag]
property is the string"Intl.ListFormat"
. This property is used inObject.prototype.toString()
.
Instance methods
Intl.ListFormat.prototype.format()
-
Returns a language-specific formatted string representing the elements of the list.
Intl.ListFormat.prototype.formatToParts()
-
Returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
Intl.ListFormat.prototype.resolvedOptions()
-
Returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current
Intl.ListFormat
object.
Examples
Using format
The following example shows how to create a List formatter using the English language.
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
Using formatToParts
The following example shows how to create a List formatter returning formatted parts
const list = ["Motorcycle", "Bus", "Car"];
console.log(
new Intl.ListFormat("en-GB", {
style: "long",
type: "conjunction",
}).formatToParts(list),
);
// [ { "type": "element", "value": "Motorcycle" },
// { "type": "literal", "value": ", " },
// { "type": "element", "value": "Bus" },
// { "type": "literal", "value": ", and " },
// { "type": "element", "value": "Car" } ];
Specifications
| Specification |
|---|
| ECMAScript® 2026 Internationalization API Specification # listformat-objects |