[PS] 숫자를 한국어로 바꾸기

doongdoong·2일 전
0

문제

3,298억 7,654만 3,210와 같이 숫자를 한국어로 표현해보자.

풀이


function commaizeNumber(num) {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function formatBillion(num) {
  return num.toString().replace(/\B(?=(\d{4})+(?!\d))/g, " ");
}

function formatToKoreanNumber(num) {
  /* 이 함수를 구현해주세요 */
  const numStr = num.toString();
  if (numStr.length > 4) {
    const bigAmount = numStr.slice(0, numStr.length - 4);
    const formatted = formatBillion(bigAmount).split(" ");

    let resultBillion = "";
    if (formatted.length > 1) {
      const billion = formatted[0];
      resultBillion = billion ? `${commaizeNumber(billion)}` : "";
    }

    let million =
      formatted.length > 1
        ? commaizeNumber(Number(formatted[1]))
        : commaizeNumber(Number(bigAmount));
    const resultMillion = Number(million) === 0 ? "" : `${million}`;

    const smallAmount = Number(numStr.slice(numStr.length - 4, numStr.length));
    const resultSmallNumber =
      smallAmount === 0 ? "" : commaizeNumber(smallAmount);

    const result = resultBillion + resultMillion + resultSmallNumber;

    return result.replace(/\s+$/, "");
  }

  return commaizeNumber(numStr);
}

console.log(formatToKoreanNumber(329876543210));
console.log(formatToKoreanNumber(98276543210));
console.log(formatToKoreanNumber(1000233445));
console.log(formatToKoreanNumber(102343000));
console.log(formatToKoreanNumber(12433333));
console.log(formatToKoreanNumber(1333234));
console.log(formatToKoreanNumber(130004));
console.log(formatToKoreanNumber(13334));
console.log(formatToKoreanNumber(1334));
console.log(formatToKoreanNumber(134));
console.log(formatToKoreanNumber(13));
console.log(formatToKoreanNumber(1));
console.log(formatToKoreanNumber(10000));
console.log(formatToKoreanNumber(100000));
console.log(formatToKoreanNumber(1000000));
console.log(formatToKoreanNumber(10000000));
console.log(formatToKoreanNumber(100000000));
console.log(formatToKoreanNumber(1000000000));
console.log(formatToKoreanNumber(10000000000));
console.log(formatToKoreanNumber(100000000000));
profile
PS 연습장

0개의 댓글