Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

인도 통화 숫자를 영어 단어로 변환하는 JavaScript 함수 – Lakh·Crore 단위 지원


문제 개요

소수점 이하 두 자리까지의 정밀도를 가진 부동소수점 숫자를 입력받아, 해당 숫자를 인도 통화 표기 방식의 영어 텍스트로 변환하는 JavaScript 함수를 작성해야 합니다.

인도의 숫자 체계는 서구권과 달리 Lakh(십만), Crore(천만) 같은 고유한 단위를 사용하기 때문에, 단순한 thousand/million 방식의 변환으로는 처리할 수 없습니다. 이 글에서는 인도식 자릿수 체계에 맞춰 숫자를 단어로 바꾸는 함수를 예제와 함께 살펴봅니다.

예시

입력 숫자가 다음과 같다면 −

const num = 12500;

출력 결과는 다음과 같아야 합니다 −

const output = 'Twelve Thousand Five Hundred';

전체 코드

다음은 위 요구 사항을 구현한 전체 코드입니다 −

const num = 12500;
const wordify = (num) => {
    const single = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];
    const double = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
    const tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
    const formatTenth = (digit, prev) => {
        return 0 == digit ? "" : " " + (1 == digit ? double[prev] : tens[digit])
    };
    const formatOther = (digit, next, denom) => {
        return (0 != digit && 1 != next ? " " + single[digit] : "") + (0 != next || digit > 0 ? " " + denom : "")
    };
    let res = "";
    let index = 0;
    let digit = 0;
    let next = 0;
    let words = [];
    if (num += "", isNaN(parseInt(num))){
        res = "";
    }
    else if (parseInt(num) > 0 && num.length <= 10) {
        for (index = num.length - 1; index >= 0; index--) switch (digit = num[index] - 0, next = index > 0 ? num[index - 1] - 0 : 0, num.length - index - 1) {
            case 0:
                words.push(formatOther(digit, next, ""));
            break;
            case 1:
                words.push(formatTenth(digit, num[index + 1]));
                break;
            case 2:
                words.push(0 != digit ? " " + single[digit] + " Hundred" + (0 != num[index + 1] && 0 != num[index + 2] ? " and" : "") : "");
                break;
            case 3:
                words.push(formatOther(digit, next, "Thousand"));
                break;
            case 4:
                words.push(formatTenth(digit, num[index + 1]));
                break;
            case 5:
                words.push(formatOther(digit, next, "Lakh"));
                break;
            case 6:
                words.push(formatTenth(digit, num[index + 1]));
                break;
            case 7:
                words.push(formatOther(digit, next, "Crore"));
                break;
            case 8:
                words.push(formatTenth(digit, num[index + 1]));
                break;
            case 9:
                words.push(0 != digit ? " " + single[digit] + " Hundred" + (0 != num[index + 1] || 0 != num[index + 2] ? " and" : " Crore") : "")
        };
        res = words.reverse().join("")
    } else res = "";
    return res
};
console.log(wordify(num));

코드 동작 원리

핵심 로직을 정리하면 다음과 같습니다.

  • 단어 매핑 배열: 한 자리 숫자(single), 10~19(double), 십의 자리(tens)에 해당하는 영어 단어를 배열로 미리 정의해 둡니다.
  • formatTenth(): 십의 자리 숫자를 처리합니다. 십의 자리가 1이면 일의 자리 숫자와 결합해 Eleven~Nineteen 형태로, 그 외에는 Twenty~Ninety 형태로 변환합니다.
  • formatOther(): 일의 자리 숫자와 단위(Thousand, Lakh, Crore 등)를 조합해 문자열을 생성하며, 앞 자리가 1일 때의 중복 표기를 방지합니다.
  • 자릿수 순회: 숫자를 문자열로 변환한 뒤 맨 뒷자리부터 한 글자씩 순회하고, 자릿수 위치(case 0~9)에 따라 Hundred, Thousand, Lakh, Crore 단위를 붙여 words 배열에 차례로 저장합니다.
  • 결합: 마지막에 words 배열을 역순으로 뒤집은 뒤 join()으로 하나의 문자열로 합쳐 최종 결과를 반환합니다.

참고로 이 함수는 최대 10자리, 즉 약 99 Crore(9억 9천만) 범위까지의 정수를 처리할 수 있으며, 유효하지 않은 입력이 들어오면 빈 문자열을 반환합니다.

실행 결과

콘솔에 출력된 결과는 다음과 같습니다 −

Twelve Thousand Five Hundred