大网数据广告活动
Web 标准与前端开发

Intl.NumberFormat.prototype.formatRange()

· 52CE 我爱测

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

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

Syntax

formatRange(startRange, endRange)

Parameters

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

Return value

A string representing the given range of numbers formatted according to the locale and formatting options of this Intl.NumberFormat object. If the start and end values are formatted to the same string, the output will only contain a single value, possibly prefixed with an "approximately equals" symbol (e.g., "~$3"). The insertion of this symbol only depends on the locale settings, and is inserted even when startRange === endRange.

Exceptions

  • RangeError
    • : Thrown if either startRange or endRange is NaN or an inconvertible string.
  • TypeError
    • : Thrown if either startRange or endRange is undefined.

Description

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

Examples

Using formatRange

Use the formatRange method for formatting a range of currency values:

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

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

// Note: the "approximately equals" symbol is added if
// startRange and endRange round to the same values.
console.log(nf.formatRange(2.9, 3.1)); // "~$3"
const nf = new Intl.NumberFormat("es-ES", {
  style: "currency",
  currency: "EUR",
  maximumFractionDigits: 0,
});

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

Specifications

Browser compatibility

See also

  • Intl.NumberFormat
  • Number.prototype.toLocaleString()

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。