Intl.NumberFormat.prototype.formatRange()

Baseline 2023
新推出

自 2023 年 8 月起,此功能已在最新的设备和浏览器版本中可用。此功能可能不适用于旧设备或浏览器。

formatRange() 方法属于 Intl.NumberFormat 实例,它根据此 Intl.NumberFormat 对象的区域设置和格式化选项来格式化数字范围。

语法

js
formatRange(startRange, endRange)

参数

startRange

要格式化的 NumberBigInt 或字符串。字符串的解析方式与 数字转换 中的方式相同,但 formatRange() 将使用字符串表示的精确值,避免在隐式转换为数字时丢失精度。

endRange

要格式化的 NumberBigInt 或字符串。

返回值

一个字符串,表示根据此 Intl.NumberFormat 对象的区域设置和格式化选项格式化后的给定数字范围。如果起始值和结束值的格式化结果相同,则输出仅包含单个值,前面可能带有“约等于”符号(例如,“~$3”)。该符号的插入仅取决于区域设置,即使 startRange === endRange 也会插入。

异常

RangeError

如果 startRangeendRangeNaN 或无法转换的字符串,则抛出此错误。

TypeError

如果 startRangeendRange 为 undefined,则抛出此错误。

描述

formatRange getter 函数根据调用它的 Intl.NumberFormat 对象的区域设置和格式化选项,将数字范围格式化为字符串。

示例

使用 formatRange

使用 formatRange getter 函数来格式化货币值范围

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

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

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

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

规范

规范
ECMAScript® 2026 国际化 API 规范
# sec-intl.numberformat.prototype.formatrange

浏览器兼容性

另见