Computer/Web [javascript]숫자 단위마다 콤마 삽입 상Q 2013. 9. 10. 23:45 // 숫자 타입에서 쓸 수 있도록 format() 함수 추가 Number.prototype.format = function(){ if(this==0) return 0; var reg = /(^[+-]?\d+)(\d{3})/; var n = (this + ''); while (reg.test(n)) n = n.replace(reg, '$1' + ',' + '$2'); return n; }; // 문자열 타입에서 쓸 수 있도록 format() 함수 추가 String.prototype.format = function(){ var num = parseFloat(this); if( isNaN(num) ) return "0"; return num.format(); }; // 숫자 타입 test var num = 123456.012; console.log(num.format()); // 123,456.012 num = 13546745; console.log(num.format()); // 13,546,745 // 문자열 타입 test console.log("12348".format()); // 12,348 console.log("12348.6456".format()); // 12,348.6456 저작자표시 비영리 변경금지 (새창열림)