Say you have a number like 10
, and it represents the price of something.
假设您有一个类似10
的数字,它表示某物的价格。
You want to transform it to $10,00
.
您想将其转换为$10,00
。
If the number has more than 3 digits however it should be displayed differently, for example 1000
should be displayed as $1,000.00
如果数字多于3位,则应以不同的方式显示,例如应将$1,000.00
1000
显示为$1,000.00
This is in USD, however.
但是,这是美元。
Different countries have different conventions to display values.
不同的国家有不同的惯例来显示价值 。
JavaScript makes it very easy for us with the ECMAScript Internationalization API, a relatively recent browser API that provides a lot of internationalization features, like dates and time formatting.
JavaScript通过ECMAScript国际化API (它是一种相对较新的浏览器API)对我们来说非常容易,该API提供了许多国际化功能,例如日期和时间格式,这是一个相对较新的浏览器API。
It is very well supported:
它得到很好的支持:
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2
})
formatter.format(1000) // "$1,000.00"
formatter.format(10) // "$10.00"
formatter.format(123233000) // "$123,233,000.00"
The minimumFractionDigits
property sets the fraction part to be always at least 2 digits. You can check which other parameters you can use in the NumberFormat MDN page.
minimumFractionDigits
属性将小数部分始终设置为至少2位数。 您可以在NumberFormat MDN页面中检查可以使用哪些其他参数。
This example creates a number formatter for the Euro currency, for the Italian country:
本示例为意大利国家/地区创建欧元货币的数字格式化程序:
const formatter = new Intl.NumberFormat('it-IT', {
style: 'currency',
currency: 'EUR'
})
翻译自: https://flaviocopes.com/how-to-format-number-as-currency-javascript/