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


基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01