Nodejs Currency Format formatCurrency(num)

Here you can find the source of formatCurrency(num)

Method Source Code

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";/*from   w  ww  . ja  va2  s  .  c  om*/
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + num + '.' + cents);
}

Related

  1. ToCurrencyWithSymbol(ccyCode, rounder)
    Number.prototype.ToCurrencyWithSymbol = function (ccyCode, rounder) {
        var symbol = ccyCode.ConvertToCurrencySymbol();
        aDigits = this.toFixed(rounder).split(".");
        aDigits[0] = aDigits[0].split("").reverse().join("")
                                        .replace(/(\d{3})(?=\d)/g, "$1,").split("").reverse().join("");
        return symbol + aDigits.join(".");
    
  2. formatCurrency()
    Number.prototype.formatCurrency = function()
      return '$' + this.toFixed(2);
    
  3. formatCurrency(c, d, t)
    Number.prototype.formatCurrency = function(c, d, t){
        var n = this,
            c = isNaN(c = Math.abs(c)) ? 2 : c,
            d = d == undefined ? "." : d,
            t = t == undefined ? "," : t,
            s = n < 0 ? "-" : "",
            i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
            j = (j = i.length) > 3 ? j % 3 : 0;
        return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
    ...
    
  4. formatCurrency(c, d, t)
    Number.prototype.formatCurrency = function(c, d, t){
      var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "",
      i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
      return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
      + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
    };