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
基础教程推荐
- fetch 是否支持原生多文件上传? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
