[js] 금액 단위에 자동으로 콤마(,)를 붙여주는 함수

JavaScript
// 숫자 타입에서 쓸 수 있도록 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();
};

.format() 을 사용하면 된다.

예제 (jQuery)

HTML

<span class="format-money">20000</span>원

Script

jQuery('.format-money').text(function() {
    jQuery(this).text(
        jQuery(this).text().format()
    );
});

결과

20,000원

formatMoney금액 컴마
블로그
프로젝트
스터디