我目前正在使用以下代码格式化数字以显示为货币值:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 Angular 2/Typescript 中使用 IScrollUse IScroll in Angular 2 / Typescript(在 Angular 2/Typescript 中使用 IScroll)
Anime.js 在 Ionic 3 项目中不起作用anime.js not working in Ionic 3 project(Anime.js 在 Ionic 3 项目中不起作用)
Ionic 3 - 使用异步数据更新 ObservableIonic 3 - Update Observable with Asynchronous Data(Ionic 3 - 使用异步数据更新 Observable)
Angular 2:在本地 .json 文件中找不到文件Angular 2: file not found on local .json file(Angular 2:在本地 .json 文件中找不到文件)
在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指In Ionic 2, how do I create a custom directive that uses Ionic components?(在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指令?)
将 ViewChild 用于动态元素 - Angular 2 &离子2Use ViewChild for dynamic elements - Angular 2 amp; ionic 2(将 ViewChild 用于动态元素 - Angular 2 amp;离子2)