Adds separation method to numbers. Allows adding separator chars for thousands, so that 1000000 becomes 1,000,000 - Node.js Number

Node.js examples for Number:Format

Description

Adds separation method to numbers. Allows adding separator chars for thousands, so that 1000000 becomes 1,000,000

Demo Code

Number.prototype.separate = function(separator) {

  var s = this.toString()

  var decimalPosition = s.indexOf(".");
  var length = s.length;

  // Check for decimals, alter "number" part length if necessary
  if (decimalPosition > -1)
    length = decimalPosition;//from  w ww  .  j av a  2 s .co  m
    
  var formattedNumber = "";
  
  // Add the decimal part first
  formattedNumber = s.substring(length, s.length);
  
  // Start adding numbers from right to left, adding separator when necessary
  for (var i = length - 1; i >= 0; i--) {  
    if ( (length - i - 1) % 3 == 0 && i != length - 1)
      formattedNumber = s.charAt(i) + separator + formattedNumber;
    else
      formattedNumber = s.charAt(i) + formattedNumber;
  }
  
  return formattedNumber;
}

Related Tutorials