Intl.NumberFormat.prototype.formatRange()
formatRange() 方法属于 Intl.NumberFormat 实例,它根据此 Intl.NumberFormat 对象的区域设置和格式化选项来格式化数字范围。
语法
js
formatRange(startRange, endRange)
参数
返回值
一个字符串,表示根据此 Intl.NumberFormat 对象的区域设置和格式化选项格式化后的给定数字范围。如果起始值和结束值的格式化结果相同,则输出仅包含单个值,前面可能带有“约等于”符号(例如,“~$3”)。该符号的插入仅取决于区域设置,即使 startRange === endRange 也会插入。
异常
RangeError-
如果
startRange或endRange是NaN或无法转换的字符串,则抛出此错误。 TypeError-
如果
startRange或endRange为 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 |
浏览器兼容性
加载中…