PS/제코베 JS 100제

제코베 JS 100제 / 58 / 콤마 찍기

KimMinJun 2022. 8. 30. 21:50

원범이는 편의점 아르바이트가 끝난 후 정산을 하고자 합니다.

정산을 빨리하고 집에 가고 싶은 원범이는 프로그램을 만들려고 합니다.

 

숫자를 입력받고 천 단위로 콤마(,)를 찍어주세요.

 

예를 들어, 123456789를 입력받았으면 123,456,789를 출력해야 합니다.

 

function printComma(n) {
  const n_str = String(n).split("").reverse();
  let result = [];
  for (let i = 1; i < n_str.length + 1; i++) {
    result.push(n_str[i - 1]);
    if (i % 3 === 0) {
      result.push(",");
    }
  }
  if (result.at(-1) === ",") result.pop();
  result.reverse();
  console.log(result.join(""));
}

const n = 123456789;
printComma(n); // 123,456,789
console.log(Number(n).toLocaleString()); // 123,456,789