Intl.NumberFormat.prototype.format()
Baseline 广泛可用 *
format() 方法是 Intl.NumberFormat 实例的一部分,它根据此 Intl.NumberFormat 对象的 区域设置和格式化选项来格式化数字。
试一试
const amount = 654321.987;
const options1 = { style: "currency", currency: "RUB" };
const numberFormat1 = new Intl.NumberFormat("ru-RU", options1);
console.log(numberFormat1.format(amount));
// Expected output: "654 321,99 ₽"
const options2 = { style: "currency", currency: "USD" };
const numberFormat2 = new Intl.NumberFormat("en-US", options2);
console.log(numberFormat2.format(amount));
// Expected output: "$654,321.99"
语法
format(number)
参数
注意: 规范的旧版本将字符串解析为 Number。请查看您浏览器的兼容性表格。
返回值
一个字符串,表示根据此 Intl.NumberFormat 对象的区域设置和格式化选项格式化后的给定 number。
注意: 大多数情况下,format() 返回的格式是一致的。然而,输出可能因实现而异,即使在同一区域设置下也是如此 — 输出差异是故意的,并且规范允许。它也可能不是您期望的。例如,字符串可能使用不间断空格,或者被双向控制字符包围。您不应将 format() 的结果与硬编码的常量进行比较。
描述
JavaScript 中的 Number 值如果太大或太小,会丢失精度,导致文本表示不准确。如果您正在对大于 Number.MAX_SAFE_INTEGER 的整数进行计算,您应该改用 BigInt,它会正确格式化。
new Intl.NumberFormat("en-US").format(1234567891234567891); // 1,234,567,891,234,568,000
new Intl.NumberFormat("en-US").format(1234567891234567891n); // 1,234,567,891,234,567,891
您也可以传递非常大的字符串以作为任意精度十进制字符串进行格式化(如果您要对数据进行计算,您仍然需要使用 BigInt)。
new Intl.NumberFormat("en-US").format("1234567891234567891"); // 1,234,567,891,234,567,891
示例
使用格式
使用 format getter 函数来格式化单个货币值。下面的代码演示了如何为俄罗斯区域设置格式化卢布货币。
const options = { style: "currency", currency: "RUB" };
const numberFormat = new Intl.NumberFormat("ru-RU", options);
console.log(numberFormat.format(654321.987));
// "654 321,99 ₽"
使用 `format` 和 `map`
使用 format getter 函数来格式化数组中的所有数字。请注意,该函数已绑定到其从中获取的 Intl.NumberFormat 对象,因此可以直接传递给 Array.prototype.map。这被认为是一个历史遗留问题,是当前不再遵循的约定的一部分,但为了保持与现有程序的兼容性而保留。
const a = [123456.789, 987654.321, 456789.123];
const numberFormat = new Intl.NumberFormat("es-ES");
const formatted = a.map((n) => numberFormat.format(n));
console.log(formatted.join("; "));
// "123.456,789; 987.654,321; 456.789,123"
使用 `format` 和字符串
使用字符串,我们可以指定大于 Number.MAX_SAFE_INTEGER 的数字,而不会丢失精度。
const numberFormat = new Intl.NumberFormat("en-US");
// Here the value is converted to a Number
console.log(numberFormat.format(987654321987654321));
// 987,654,321,987,654,300
// Here we use a string and don't lose precision
console.log(numberFormat.format("987654321987654321"));
// 987,654,321,987,654,321
我们也可以使用通用的“E”指数语法表示十进制字符串:#.#E#。下面的代码创建了一个 BigInt,将其转换为带后缀 E-6 的字符串,然后进行格式化。
const numberFormat = new Intl.NumberFormat("en-US");
const bigNum = 1000000000000000110000n;
console.log(numberFormat.format(bigNum));
// "1,000,000,000,000,000,110,000"
// Format as a string using the `E` syntax:
console.log(numberFormat.format(`${bigNum}E-6`));
// "1,000,000,000,000,000.11"
规范
| 规范 |
|---|
| ECMAScript® 2026 国际化 API 规范 # sec-intl.numberformat.prototype.format |
浏览器兼容性
加载中…