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

};


// 콤마가 들어간 문자열을 콤마 제거하면서 숫자형 반환

String.prototype.unformat = function(){

var str = this.replace(/,/g,'');

var num = parseFloat(str);

if( isNaN(num) ) {

return "0";

}


return String(num);

};

 

 

// 숫자 타입 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


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


// 숫자용
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

'Javascript' 카테고리의 다른 글

숫자에 콤마와 언콤마를 편하게  (0) 2016.06.27
정규식으로 괄호 안의 문자 추출과 치환하기  (0) 2015.07.09
형변환, 숫자체크  (0) 2014.06.26
Date Format  (0) 2014.04.04
replaceAll 구현  (0) 2013.09.05

+ Recent posts