在 JavaScript 中格式化货币,删除 .00

问题描述 投票:0回答:8

我目前正在使用以下代码格式化数字以显示为货币值:

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", "");

或者这个解决方案是最好的方法吗?

javascript string format currency-formatting
8个回答
3
投票

查看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


3
投票

您可以通过将 Intl.NumberFormat

 设置为数字整数部分的位数
,将货币四舍五入到最接近的美元(或英镑或其他)

maximumSignificantDigits


如果您使用负货币,请记住,与其他 JavaScript 方法(如
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 位小数,这在任何用例中都适用。


1
投票

现在,如果您正在处理欧元货币,那么这就是您真正想要的。

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


0
投票

根据@RobG的建议,我可以使用:


0
投票

可以通过简单的方式完成

0
投票

要删除 
Intl.NumberFormat

0
投票

(parseFloat(percentage) / 100) * product.price) .toFixed(2) .toString() .replace('.00', '')

我使用此函数,将整数的小数位强制为零,将浮点数强制为 2,结果为:

0
投票
10 被格式化为 $10

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

© www.soinside.com 2019 - 2024. All rights reserved.