Format currency in JavaScript removing .00(在 JavaScript 中格式化货币删除 .00)
问题描述
我目前正在使用以下代码格式化数字以显示为货币值:
I am currently formatting numbers to display as currency values using the following code:
return symbol + value.toFixed(2).replace(/(d)(?=(d{3})+.)/g, "$1,");
其中符号是£、$ 等,值是带有许多小数位的数字.这很好用,但我现在想删除尾随 .00
(如果存在).
where symbol is £,$ etc. and value is a number with many decimal places. This works great but I now want to remove trailing .00
if present.
目前我有这个输出:
1.23454 => £1.23
1 => £1.00
50.00001 => £50.00
2.5 => £2.50
我想要以下内容:
1.23454 => £1.23
1 => £1
50.00001 => £50
2.5 => £2.50
有没有比以下更清洁的方法:
Is there a cleaner way than:
var amount = symbol + value.toFixed(2).replace(/(d)(?=(d{3})+.)/g, "$1,");
return amount.replace(".00", "");
或者那个解决方案是最好的方法?
or is that solution the best way?
推荐答案
查看Intl.NumberFormat.这是一个非常方便的原生api.
Look into Intl.NumberFormat. It is a very handy native api.
let number = 1.23454;
console.log(new Intl.NumberFormat('en-GB', {
style: 'currency',
currency: 'GBP'
}).format(number).replace(/(.|,)00$/g, ''));
// → £1.23
这篇关于在 JavaScript 中格式化货币删除 .00的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 JavaScript 中格式化货币删除 .00
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01