我目前正在使用以下代码格式化数字以显示为货币值:
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
您可以通过将 Intl.NumberFormat
设置为数字整数部分的位数,将货币四舍五入到最接近的美元(或英镑或其他)
maximumSignificantDigits
let number = 999.50;
console.log(new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumSignificantDigits: Math.trunc(Math.abs(number)).toFixed().length,
}).format(number)); // $1,000 (rounds up because 50 cents)
)相比,
Intl.NumberFormat
具有更明智的行为:
从零舍入。例如,
Math.round
返回Math.round(999.5)
,但1000
返回Math.round(-999.5)
,而使用-999
将返回Intl.NumberFormat
和1000
。下面的原生 JS 将从任何格式化为字符串的数字中删除所有尾随 0。 NumberFormat 自动删除尾随零。我选择 20 作为 MaximumFractionDigits,因为 20 是允许的最大限制,因此只要您不处理超过 20 位小数,这在任何用例中都适用。
现在,如果您正在处理欧元货币,那么这就是您真正想要的。
new Intl.NumberFormat('en-IN', {
maximumFractionDigits: 20
}).format('20.01230000') // 20.0123
NumberFormat 不仅仅会修剪它的四舍五入,只有这样做才有意义,因此精度的损失会导致尽可能少的准确性损失。
new Intl.NumberFormat('en-IN', {
style: 'currency',
currency: 'GBP' ,
minimumFractionDigits: 0,
minimumFractionDigits: 20
}).format('20.01530000')) // 20.02
根据@RobG的建议,我可以使用:
可以通过简单的方式完成
要删除Intl.NumberFormat
10.1 被格式化为 $10.10(而不是默认的 $10.1)
let number = 50;
console.log(new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumSignificantDigits: (number + '').replace('.', '').length,
}).format(number)); // $50