如何在JavaScript中将数字格式化为货币值

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:

它得到很好的支持:

Browser support for the internationalization API
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/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值