글
[ 소스-1 ]
function comma(num){
var len, point, str;
num = num + "";
point = num.length % 3 ;
len = num.length;
str = num.substring(0, point);
while (point < len) {
if (str != "") str += ",";
str += num.substring(point, point + 3);
point += 3;
}
return str;
}
소스-1의 경우 소수점 자리적용이 안되는 문제가있다.
[ 소스-2 ]
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
[ 소스-3 ]
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
소스-2와 소스-3는 소수점까지 정확하게 처리된다.
'WEB > 자바스크립트' 카테고리의 다른 글
자바스크립트 문자열 개수 세기 (0) | 2021.01.15 |
---|
RECENT COMMENT