我目前正在使用以下代码格式化数字以显示为货币值:
return symbol + value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
其中符号为 £、$ 等,值是具有多个小数位的数字。这很好用,但我现在想删除尾随 .00
(如果存在)。
目前我有这个输出:
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
是否有比以下更简洁的方法:
var amount = symbol + value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
return amount.replace(".00", "");
或者那个解决方案是最好的方法吗?
最佳答案
查看Intl.NumberFormat .这是一个非常方便的原生 API。
let number = 1.23454;
console.log(new Intl.NumberFormat('en-GB', {
style: 'currency',
currency: 'GBP'
}).format(number).replace(/(\.|,)00$/g, ''));
// → £1.23
关于javascript - 在 JavaScript 中格式化货币删除 .00,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46235907/