Javascript

숫자에 천단위 콤마 찍기

풍풍 2014. 10. 1. 16:25
// 숫자용
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;
};

// 문자용
String.prototype.format = function(){
    var num = parseFloat(this);
    if( isNaN(num) ) return "0";
 
    return num.format();
};


사용법
var num = 1234.32;
num.format();

var str = "1234.67";
str.format();


 출처: http://stove99.tistory.com/113