카테고리 없음
[자바스크립트] 천단위 콤마 찍기 (정규식 없음)
[M]
2021. 1. 9. 17:30
인터넷에 찾아보니 정규식으로 천단위 콤마를 찍긴하지만
제대로 작동되는 코드가 없어 직접 코드를 만들어보았다.
function commafy( num ) {
let str = num.toString().split('.');
let realArr = str[0].split('').reverse();
let res = [];
for(let i = 0 ; i < str[0].length ; i++){
if(i !== 0 && i % 3 === 0 && realArr[i] !== '-'){
res.unshift(',');
}
res.unshift(realArr[i]);
}
return `${res.join('')}${str[1] ? '.' : ''}${str[1] ? str[1] : ''}`;
}
console.log(commafy("1"));
console.log(commafy(12));
console.log(commafy(12345));
console.log(commafy("12345"));
console.log(commafy("1234567"));