场景需求:
最近在项目中遇到了多语言价格格式化的需求(即$1234 => $1,234 的转换),简单的暴力处理无法满足多语言转变的需求,此时使用 Number.prototype.toLocaleString() 进行数字格式化处理再好不过。
使用 toLocaleString()
没有指定区域的基本使用时,返回使用默认的语言环境和默认选项格式化的字符串。
let price = 23500;
console.log(price.toLocaleString()); // 23,500
参数
locales 和 options 参数让应用程序可以指定要进行格式转换的语言,并且定制函数的行为。
locales参数
locales 参数收由缩写语言代码(BCP 47 language tag)的字符串或者这些字符串组成的数组
const number = 123456.789;
// 德国使用逗号作为小数分隔符,分位周期为千位
console.log(number.toLocaleString("de-DE")); // 123.456,789
// 印度使用千位/拉克(十万)/克若尔(千万)分隔
console.log(number.toLocaleString("en-IN")); // 1,23,456.789
options参数
调整输出格式的对象。
const number = 123456.789;
// 要求货币格式
console.log(
number.toLocaleString("de-DE", { style: "currency", currency: "EUR" }),
);
// 123.456,79 €
// 日元不使用小数位
console.log(
number.toLocaleString("ja-JP", { style: "currency", currency: "JPY" }),
)
// ¥123,457
// 限制三位有效数字
console.log(number.toLocaleString("en-IN", { maximumSignificantDigits: 3 })); // 1,23,000