JavaScript
JS | 화폐단위 형식으로 콤마 입력하는 법 (함수 + 브라우저api)
GROWNFRESH
2020. 9. 12. 11:03
** 브라우저 내장 객체로 함수, 정규식 보다는 아래 메소드를 쓰는 것을 추천한다.
Intl.NumberFormat
const number = 123456.789;
console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number));
developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
함수
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;
}
정규식
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
출처