JavaScript `Intl.NumberFormat`实例

153 阅读1分钟

在客户端格式化数字是一项重要的任务,特别是当你考虑到现在有多少原始的API使用量在发挥作用。 同样重要的是确保这些数字对用户来说是有意义的,无论他们身处世界何处,特别是如果你是一个电子商务网站。

编写国际化代码可能是一场噩梦,但幸运的是,JavaScript为我们提供了Intl.NumberFormat ,一个用于将数字国际化为货币的API,以及更多。让我们来看看吧!

Intl.NumberFormat 的一些例子包括。

new Intl.NumberFormat().format(12345)
// 12,345

new Intl.NumberFormat('en-US', { maximumSignificantDigits: 4}).format(1.2345678)
// 1.235 (Notice the rounding)

new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' }).format(9002.20)
// £9,002.20

new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(9002.20)
// 9.002,20 €

new Intl.NumberFormat().formatToParts(12345.678)
/*
[
   { "type":"integer", "value":"12" },
   { "type":"group", "value":"," },
   { "type":"integer", "value":"345" },
   { "type":"decimal", "value":"." },
   { "type":"fraction", "value":"678" }
]
*/

如果你想呈现的数字是标准格式,就不要费心去写你自己的客户端数字格式化函数--利用浏览器为你提供的惊人的API吧!