Nodejs Number Format numberWithCommas()

Here you can find the source of numberWithCommas()

Method Source Code

/**//from  w  ww.  ja  v a 2s  . c om
 * Created by rappresent on 12/16/14.
 */

String.prototype.numberWithCommas = function () {
   if (typeof parseFloat(this) === "number") {
      thiss = (Math.round((this) * 100) / 100).toString();
      var dotLastIndex = this.lastIndexOf(".");
      if (dotLastIndex === -1) {
         thiss = this + ".00"
      } else {
         var decimal = this.substring(dotLastIndex+1);
         var nonDecimal = this.substring(0, dotLastIndex);
         thiss = nonDecimal + "." + decimal;

         if (this[this.lastIndexOf(".")+2] == undefined) {
            thiss = this + "0"
         }
      }

      var parts = this.toString().split(",");
      parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      return parts.join(".");
   } else {
      console.log(this, ": please only number")
   }
};

Related

  1. formatted()
    Number.prototype.formatted = function(){
      if (!this) return 0;
      var sign   = this < 0 ? '-' : '',
        num    = Math.floor(Math.abs(this)*100+0.50000000001),
        cents  = (num % 100).toString().substring(0, 2);
      num = Math.floor(num/100).toString();
      for (var i = 0, l = Math.floor((num.length-1)/3), p = 3; i < l; i++, p += 4){
        num = num.substring(0, num.length - p) + ' ' + num.substring(num.length - p);
      return sign + num + '.' + (cents < 10 ? '0' + cents : cents);
    };
    
  2. toSize()
    Object.defineProperty( Number.prototype, "toSize", {
        "get": function() {
            return function( bitsNotBytes ) {
                var sizes = ['', ' Kb', ' Mb', ' Gb', ' Tb', ' Pb' ];
                var unit  = 0, remain = Math.abs( this * 1 );
                if ( bitsNotBytes )
                    remain *= 8;
                while ( remain >= 1024 && unit<5 )
                    remain /= 1024, unit++;
    ...
    
  3. CommaFormatted(n,symbol)
    Number.prototype.CommaFormatted = function(n,symbol) {
      return (symbol || '\uffe5') + this.toFixed(n === void 0 ? 2 : n).toString().replace(/(\d)(?=(\d{3})+($|\.))/g, '$1,');
    };
    (4564546).CommaFormatted(2,"$");
    
  4. numberFormat()
    String.prototype.numberFormat=function() {
       return this.replace(/(\d)(?=(?:\d{3})+(?!\d))/g,'$1,');
    function numberformatter(vNum){
      return String(vNum).numberFormat();
    
  5. numberFormat()
    String.prototype.numberFormat = function() {
        return this.replace(/(\d)(?=(?:\d{3})+(?!\d))/g,'$1,');
    };