javascript

자바스크립트 numberformat 상속 확장

이상욱1 2016. 6. 8. 13:17
자바스크립트 numberformat 상속 확장 해서 쓴 경우 
http://stove99.tistory.com/113
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 숫자 타입에서 쓸 수 있도록 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