diff --git a/.changeset/curvy-bats-nail.md b/.changeset/curvy-bats-nail.md new file mode 100644 index 00000000..f1031f66 --- /dev/null +++ b/.changeset/curvy-bats-nail.md @@ -0,0 +1,5 @@ +--- +"es-hangul": patch +--- + +fix: amountToHangul이 선행 0이 있는 문자열을 잘못 변환하는 오류를 수정합니다. diff --git a/src/amountToHangul.spec.ts b/src/amountToHangul.spec.ts index f7c47c24..eae4c5ad 100644 --- a/src/amountToHangul.spec.ts +++ b/src/amountToHangul.spec.ts @@ -10,10 +10,10 @@ describe('amountToHangul', () => { }); it('숫자로 된 금액이 80글자를 넘을 시 에러 발생', () => { - const longNumberString = '1'.repeat(81); + const longNumberString = '1'.repeat(81); expect(() => amountToHangul(longNumberString)).toThrowError(`convert range exceeded : ${longNumberString}`); - }) - + }); + it('숫자 외 문자를 무시하여 반환', () => { expect(amountToHangul('120,030원')).toEqual('일십이만삼십'); }); @@ -31,4 +31,10 @@ describe('amountToHangul', () => { expect(amountToHangul(100000100)).toEqual('일억백'); expect(amountToHangul(392.24)).toEqual('삼백구십이점이사'); }); + + it('선행 0이 있는 경우 처리', () => { + expect(amountToHangul('01023')).toEqual('일천이십삼'); + expect(amountToHangul('001023')).toEqual('일천이십삼'); + expect(amountToHangul('0001023')).toEqual('일천이십삼'); + }); }); diff --git a/src/amountToHangul.ts b/src/amountToHangul.ts index 3d70f9d5..ca43b335 100644 --- a/src/amountToHangul.ts +++ b/src/amountToHangul.ts @@ -26,19 +26,21 @@ export const HANGUL_NUMBERS_FOR_DECIMAL = ['영', '일', '이', '삼', '사', ' export const HANGUL_CARDINAL = ['', '십', '백', '천']; export function amountToHangul(amount: string | number) { - const [integerPart, tempDecimalPart] = String(amount) + const [rawIntegerPart, rawDecimalPart] = String(amount) .replace(/[^\d.]+/g, '') .split('.'); + const integerPart = rawIntegerPart !== '0' ? rawIntegerPart.replace(/^0+/, '') : rawIntegerPart; + if (integerPart.length > HANGUL_DIGITS_MAX) { throw new Error(`convert range exceeded : ${amount}`); } - const decimalPart = tempDecimalPart?.replace(/0+$/, ''); + const decimalPart = rawDecimalPart?.replace(/0+$/, ''); const result = []; let pronunDigits = true; - if(integerPart === '0' || (integerPart === '' && tempDecimalPart)) { + if (integerPart === '0' || (integerPart === '' && rawDecimalPart)) { result.push(HANGUL_NUMBERS_FOR_DECIMAL[0]); } else { for (let i = 0; i < integerPart.length - 1; i++) {