우리가 서버로부터 데이터를 가져와서 브라우저에 숫자를 보여주는 경우 100000을 1,000,000과 보여주고 싶은 경우가 빈번하게 발생한다. 다양한 방법에 대해서 알아보도록 하자!
1. 정규 표현식을 활용한 방법
function numberWithCommas(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
2. toLocaleString()
const num = 123456789;
console.log(num.toLocaleString());
3. Intl.NumberFormat( ).format( )
최근에 많이 사용하는 방법이며, format의 인자부분에 숫자, 문자열 타입 둘 모두 처리 해주게 된다.
console.log(new Intl.NumberFormat().format("123456789"));
console.log(new Intl.NumberFormat().format(123456789));
4. 재귀함수를 활용한 방법
function comma(s) {
if (s.length <= 3) {
return s;
} else {
return comma(s.slice(0, s.length - 3)) + "," + s.slice(s.length - 3);
}
}
console.log(comma("123456789"));
5. 실제 프로젝트에서 적용된 유틸함수
아래의 코드는 제가 실제로 숫자 Format형태를 변경하기 위해서 사용한 유틸함수입니다.
export const priceFormat = (num) => {
if (isNaN(num)) {
return "-";
}
if (typeof num === "number") {
return new Intl.NumberFormat().format(num);
}
return "-";
};
6. Remind
Comma를 찍는 방법이 정말 다양하게 존재한다는 것을 알게 되었다. 재귀적으로 처리하는 방법밖에 알지 못했었지만, 자바스크립트 내부에도 사용할 수 있는 메소드들이 조금 더 처리를 하기에는 직관적인거 같고 간단하기 때문에 앞으로 유용하게 사용할 것 같다.
'Programming > JavaScript' 카테고리의 다른 글
Deep copy와 Shallow copy (0) | 2024.03.29 |
---|---|
Call by reference와 Call by value의 차이 (0) | 2024.03.17 |
빈칸을 채우기 위한 padStart, padEnd (0) | 2022.11.17 |