实现说明
演示用的数据放在这几个模块级绑定中: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')));