我需要附加一个小数,但带有逗号,所以如果是 300 它应该更改为 300,00 我有下面的代码并且它可以工作,但是如果number 已经是小数,它会将其更改为 NAN。我需要代码不修改已经是小数的数字
var formatter = new Intl.NumberFormat('es-ES', {
style: 'currency',
currency: 'USD',
});
$('.total-amount').each(function() {
var x = $(this).text().replace(/[^\d,]/g, "");
$(this).text(formatter.format(x));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="total-in-basket">
<div class="total-description">
total is:
</div>
<p> with decimal example: </p>
<div class="total-amount">
$ 300,00
</div>
<p> without decimal example: </p>
<div class="total-amount">
$ 300
</div>
</div>
最佳答案
您只需再添加一个额外的replace
即可替换 ( , ) 之后的尾随文本
示例:
var formatter = new Intl.NumberFormat('es-ES', {
style: 'currency',
currency: 'USD',
});
$('.total-amount').each(function() {
var x = $(this).text().replace(/[^\d,]/g,"").replace(/,.*$/g,""); /*<- add this*/
$(this).text(formatter.format(x));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="total-in-basket">
<div class="total-description">
total is:
</div>
<p> with decimal example: </p>
<div class="total-amount">
$ 300,00
</div>
<p> without decimal example: </p>
<div class="total-amount">
$ 300
</div>
</div>
关于javascript - 如果是整数则追加 ,00,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55979319/