Ahamed Zulfan
Ahamed Zulfan

Reputation: 135

Format JS result into Currency Format

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)

http://jsfiddle.net/2c6p928x/

Upvotes: 0

Views: 350

Answers (2)

chridam
chridam

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');

});

JSFiddle

Upvotes: 1

agershun
agershun

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

Related Questions