数字在特定的语言环境下格式化方法 Intl.NumberFormat

465 阅读2分钟

之前经常处理数字和币种,突然发现Intl.NumberFormat 这个方法巨好用,主要是兼容性还不赖。感觉可以在业务逻辑里面使用起来。于是做个读书笔记📒

Intl.NumberFormat

Intl.NumberFormat 对象能使数字在特定的语言环境下格式化。

尝试一下

const number = 123456.789;

console.log(
  new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(
    number,
  ),
);
// Expected output: "123.456,79 €"

// The Japanese yen doesn't use a minor unit
console.log(
  new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(
    number,
  ),
);
// Expected output: "¥123,457"

// Limit to three significant digits
console.log(
  new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(
    number,
  ),
);
// Expected output: "1,23,000"

构造函数

Intl.NumberFormat() (en-US)

创建一个新的 NumberFormat 对象。

示例

基础用例

在不指定区域设置的基本用例中,返回默认区域和默认选项中的格式化字符串。

JSCopy to Clipboard

const number = 3500;
console.log(new Intl.NumberFormat().format(number));// 如果在美式英语区域 → '3,500'

使用 locales

此示例展示了本地数字格式化的一些变化。为了得到用户应用接口使用的语言格式,请确保使用 locales 参数指定该语言(可能还有一些备选语言):

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

使用 options

可以使用 options (en-US) 参数自定义结果:

JSCopy to Clipboard

const number = 123456.789;

// 要求货币格式
console.log(
  new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(
    number,
  ),
);
// 123.456,79 €

// 日元不使用小数位
console.log(
  new Intl.NumberFormat("ja-JP", { style: "currency", currency: "JPY" }).format(
    number,
  ),
);
// ¥123,457

// 限制三位有效数字
console.log(
  new Intl.NumberFormat("en-IN", { maximumSignificantDigits: 3 }).format(
    number,
  ),
);
// 1,23,000

// 带有单位的格式化
console.log(
  new Intl.NumberFormat("pt-PT", {
    style: "unit",
    unit: "kilometer-per-hour",
  }).format(50),
);
// 50 km/h

console.log(
  (16).toLocaleString("en-GB", {
    style: "unit",
    unit: "liter",
    unitDisplay: "long",
  }),
);
// 16 litres

浏览器兼容性

caniuse.com/?search=Int…