Add Commas to Number

by Marcel Ferdinand

HTML

<button>test</button>
<input id="priceInput" type="text">
<input id="priceInputAuto" type="text">

JavaScript

// Add comma to output
//-------------------------------------------------------------------//
function addCommas(num) {
    var str = num.toString().split('.');
    if (str[0].length >= 4) {
        //add comma every 3 digits befor decimal
        str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
    }
    /* Optional formating for decimal places
    if (str[1] && str[1].length >= 4) {
        //add space every 3 digits after decimal
        str[1] = str[1].replace(/(\d{3})/g, '$1 ');
    }*/
    return str.join('.');
}

var priceInput;
$('button').on('click', function(){
priceInput = document.getElementById("priceInput").value;
    alert(addCommas(priceInput));
});




$(document).ready(function(){


    $('#priceInputAuto').keyup(function(event){
      // skip for arrow keys
      if(event.which >= 37 && event.which <= 40){
          event.preventDefault();
      }
      var $this = $(this);
      var num = $this.val().replace(/,/gi, "").split("").reverse().join("");

      var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));

      // the following line has been simplified. Revision history contains original.
      $this.val(num2);});});

    function RemoveRougeChar(convertString){


    if(convertString.substring(0,1) == ","){

        return convertString.substring(1, convertString.length)            

    }
    return convertString;

}