使用Intl.NumberFormat对数字进行格式化

Intl 对象是 ECMAScript 国际化 API 的一个命名空间,它提供了精确的字符串对比、数字格式化,和日期时间格式化。Collator,NumberFormat 和 DateTimeFormat 对象的构造函数是 Intl 对象的属性。

这里我用几个有用的函数来展示Intl.NumberFormat(数字格式化)的用法

根据浏览器环境语言自动切换

在浏览器环境中,我们可以读取现在使用的语言。自动使用对应的语言进行格式化

js
export const numberFormatter = new Intl.NumberFormat(navigator.language, {
    notation: "compact",
});

金钱格式化

对金钱的格式化,可以要求使用什么货币格式进行格式化

不同语种

让Intl对各种语言进行数字的格式化,在多语言环境中无需额外考虑不同语种格式化的问题

js
const number = 123456.789;

// 德语使用逗号(,)作为小数点,使用句号(.)作为千位分隔符
console.log(new Intl.NumberFormat("de-DE").format(number));
// → 123.456,789

// 大多数阿拉伯语国家使用阿拉伯语数字
console.log(new Intl.NumberFormat("ar-EG").format(number));
// → ١٢٣٤٥٦٫٧٨٩

// India uses thousands/lakh/crore separators
console.log(new Intl.NumberFormat("en-IN").format(number));
// → 1,23,456.789

// 通过编号系统中的 nu 扩展键请求,例如:中文十进制数字
console.log(new Intl.NumberFormat("zh-Hans-CN-u-nu-hanidec").format(number));
// → 一二三,四五六.七八九

// 当请求的语言不被支持,例如巴里,包含一个回滚语言印尼,这时候就会使用印尼语
console.log(new Intl.NumberFormat(["ban", "id"]).format(number));
// → 123.456,789

携带单位

可以带单位进行格式化

js
console.log(
    new Intl.NumberFormat("pt-PT", {
        style: "unit",
        unit: "kilometer-per-hour",
    }).format(50),
);
// 50 km/h
【翻译】如何构建大型 Vue 应用程序
使用 chatgpt 制作自己的小贴纸