Edits the number prototype to allow money formatting - Node.js Number

Node.js examples for Number:Currency

Description

Edits the number prototype to allow money formatting

Demo Code

/**/*  w  ww.j  av  a  2s. c om*/
* Edits the number prototype to allow money formatting
*
* @param fixed the number to fix the decimal at. Default 2.
* @param decimalDelim the string to deliminate the non-decimal
*        parts of the number and the decimal parts with. Default "."
* @param breakdDelim the string to deliminate the non-decimal
*        parts of the number with. Default ","
* @return returns this number as a USD-money-formatted String
*      like this: x,xxx.xx
*/
Number.prototype.money = function(fixed, decimalDelim, breakDelim){
  var n = this, 
  fixed = isNaN(fixed = Math.abs(fixed)) ? 2 : fixed, 
  decimalDelim = decimalDelim == undefined ? "." : decimalDelim, 
  breakDelim = breakDelim == undefined ? "," : breakDelim, 
  negative = n < 0 ? "-" : "", 
  i = parseInt(n = Math.abs(+n || 0).toFixed(fixed)) + "", 
  j = (j = i.length) > 3 ? j % 3 : 0;
  return negative + (j ? i.substr(0, j) +
     breakDelim : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + breakDelim) +
      (fixed ? decimalDelim + Math.abs(n - i).toFixed(fixed).slice(2) : "");
}

Related Tutorials