Reputation: 180
I need to append .00
if number is not decimal, however when I try the code below it is changing the whole number to 0.00
. For example, if number is 12,200
, it will change it to 0.00
instead of adding .00
at the end
$('.total-amount').each(function() {
var x = Number($(this).val()).toFixed(2);
$(this).val(x).text(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>
<div class="total-amount">
$ 12,200
</div>
</div>
Upvotes: 0
Views: 78
Reputation: 350137
Some issues:
div
has no value
attribute so .val()
will not work. Use .text()
Number
to something that has a dollar sign or a comma will return NaN
You can use replace
to remove the non-digit characters (but allowing a decimal point), and then feed that to a formatter, provided by Intl.NumberFormat
:
var formatter = new Intl.NumberFormat('en-US', {
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>
<div class="total-amount">
$ 12,200
</div>
</div>
Upvotes: 4