Format Numbers as money in JavaScript

Posted On // Leave a Comment


Decimal Values
var profits=2489.8237
  profits.toFixed(3) //returns 2489.824 (round up)
  profits.toFixed(2) //returns 2489.82
  profits.toFixed(7) //returns 2489.8237000 (padding)
Thousand Separator
Number.prototype.formatMoney = 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) : "");
 };
And use it with :
(123456789.12345).formatMoney(2, '.', ',');
If you're always going to use '.' and ',', you can leave them off your method call, the method will default them for you.
(123456789.12345).formatMoney(2);
If your culture has the two symbols flipped (i.e. Europeans), just paste over the following two lines in the formatMoney method:
 d = d == undefined ? "," : d, 
    t = t == undefined ? "." : t, 
sources : http://stackoverflow.com

0 komentar: