commafy

Add comma to number in javascript

by runsun

JavaScript

function commafy( num){
    var parts = (''+ (num<0?-num:num)).split("."), s=parts[0], i=L= s.length, o='',c;
  while(i--){ o = (i==0?'':((L-i)%3?'':',')) 
                  +s.charAt(i) +o }
    return (num<0?'-':'') + o + (parts[1] ? '.' + parts[1] : ''); 
}
$('body').html(
    commafy(-123456) + "<br/>"+ 
    commafy(-1234567.2345) + "<br/>"+ 
    commafy(343535353.5388)+ "<br/>"+ 
    commafy(123456789.01)
);