Reputation: 135
I want to convert the format of the result into currency. JS
$(function(){
function credit (selector) {
$(selector).each(function () {
var total = 0,
column = $(this).siblings(selector).andSelf().index(this);
$(this).parents().prevUntil(':has(' + selector + ')').each(function () {
total += parseFloat($('td.credit:eq(' + column + ')', this).html()) || 0;
})
$(this).html(total);
});
}
credit('td.creditsubtotal');
credit('td.credittotal');
});
The result is show in a class tag. I want it to be shown in a currency format. Eg. $ x,xxx.xx ($ 1,234.56)
Upvotes: 0
Views: 350
Reputation: 103375
Something like this should do the trick:
$(function(){
function credit (selector) {
$(selector).each(function () {
var total = 0,
formattedTotal, numCredit, strCredit
column = $(this).siblings(selector).andSelf().index(this);
$(this).parents().prevUntil(':has(' + selector + ')').each(function () {
strCredit = $('td.credit:eq(' + column + ')', this).html() || "";
console.log(strCredit);
numCredit = Number(strCredit.replace(/[^0-9\.]+/g,""));
console.log(numCredit);
total += parseFloat(numCredit) || 0;
})
formattedTotal = total.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
$(this).html('$'+formattedTotal);
});
}
credit('td.creditsubtotal');
credit('td.credittotal');
});
Upvotes: 1
Reputation: 4107
You can use Numeral.js library.
This is an example, how to format the total
variable in currency format:
$(this).html(numeral(total).format('$0,0.00'));
It is only 3k, but supports multiple different formats and has localizations.
Upvotes: 1