Skip to content

Commit

Permalink
fix: amountToHangul이 선행 0이 있는 문자열을 잘못 변환하는 오류를 수정합니다. (#168)
Browse files Browse the repository at this point in the history
* fix: 호환성을 위해 배열의 마지막 요소 가져오는 부분 수정

* fix: 선행 0도 처리 가능하도록 amountToHangul 수정

* test: 선행 0 처리 테스트 코드 추가

* fix: 변수 네이밍 수정

* Create curvy-bats-nail.md

---------

Co-authored-by: 박찬혁 <[email protected]>
  • Loading branch information
jungwoo3490 and okinawaa committed Jul 13, 2024
1 parent 7edf9b9 commit bb35458
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/curvy-bats-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"es-hangul": patch
---

fix: amountToHangul이 선행 0이 있는 문자열을 잘못 변환하는 오류를 수정합니다.
12 changes: 9 additions & 3 deletions src/amountToHangul.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('일십이만삼십');
});
Expand All @@ -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('일천이십삼');
});
});
8 changes: 5 additions & 3 deletions src/amountToHangul.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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++) {
Expand Down

0 comments on commit bb35458

Please sign in to comment.