← 中文资源

简体中文版本

formatRange 渲染数值区间

formatRange 把两个数渲染成一段本地化区间:单位与百分号两端各留一份、日期区间还会收尾缩写,不用手动拼接两个格式化结果。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

1,200–5,600
1–5 GB
12.3% – 45.6%
Nov 1 – 20

实现说明

演示用的数据放在这几个模块级绑定中:nf、disk、pct、df。

常见问题

这个示例需要哪些包?

一个都不用。代码用到的符号都在标准库里解析。 文件用顶层绑定保存自己的状态:nf、disk、pct。

核心语句

const disk = new Intl.NumberFormat('en-US', { style: 'unit', unit: 'gigabyte' });
const df = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric' });
const pct = new Intl.NumberFormat('en-US', {
  style: 'percent',
  maximumFractionDigits: 1,
});

代码示例

// formatRange renders two numbers as one localized range instead of
// concatenating two separately formatted values.
const nf = new Intl.NumberFormat('en-US');

console.log(nf.formatRange(1200, 5600));

// Units collapse the same way: a single "1–5 GB", not "1 GB – 5 GB"
const disk = new Intl.NumberFormat('en-US', { style: 'unit', unit: 'gigabyte' });
console.log(disk.formatRange(1, 5));

// Percent ranges keep a % on both ends of the dash
const pct = new Intl.NumberFormat('en-US', {
  style: 'percent',
  maximumFractionDigits: 1,
});
console.log(pct.formatRange(0.123, 0.456));

// Date ranges work through Intl.DateTimeFormat.formatRange
const df = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric' });
console.log(df.formatRange(new Date('2026-11-01'), new Date('2026-11-20')));