/ Published in: JavaScript
A quick function that makes it easy to convert an integer into a number string with commas inserted.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function number_with_commas(n){ var m = Math.abs(n); var sign = n < 0 ? '-' : ''; var output = ""; var chars = String(m).split('').reverse(); var commas = Math.floor((chars.length-1) / 3); var i = 0; for(i=0; i<commas; i++){ output = output + chars.slice(0,3).join('') + ','; chars = chars.slice(3); } output = output + chars.join(''); return sign + output.split('').reverse().join(''); }