From 812c0c22b200999ca36ed56d14a19ebbcca75100 Mon Sep 17 00:00:00 2001 From: Paras Agarwal Date: Wed, 29 Jul 2026 08:42:19 +0530 Subject: [PATCH] fix(number-to-words): accept leading/trailing decimal points Normalize edge-case decimal inputs so '.25' is read as 'zero point two five' and '5.' as 'five'. A lone '.' is still rejected. Adds 3 tests. Co-authored-by: rebelroot <262209644+rebelroot@users.noreply.github.com> --- .../number-to-words.service.test.ts | 16 ++++++++++++++++ .../tools/number/number-to-words/service.ts | 10 ++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/pages/tools/number/number-to-words/number-to-words.service.test.ts b/src/pages/tools/number/number-to-words/number-to-words.service.test.ts index 9015a0a3..1db62c6d 100644 --- a/src/pages/tools/number/number-to-words/number-to-words.service.test.ts +++ b/src/pages/tools/number/number-to-words/number-to-words.service.test.ts @@ -105,4 +105,20 @@ describe('numberToWords', () => { '' ); }); + + it('supports a leading decimal point', () => { + expect(numberToWords('.25', { uppercase: false, includeAnd: true })).toBe( + 'zero point two five' + ); + }); + + it('supports a trailing decimal point', () => { + expect(numberToWords('5.', { uppercase: false, includeAnd: true })).toBe( + 'five' + ); + }); + + it('rejects a lone dot', () => { + expect(numberToWords('.', { uppercase: false, includeAnd: true })).toBe(''); + }); }); diff --git a/src/pages/tools/number/number-to-words/service.ts b/src/pages/tools/number/number-to-words/service.ts index b04e2717..764d1251 100644 --- a/src/pages/tools/number/number-to-words/service.ts +++ b/src/pages/tools/number/number-to-words/service.ts @@ -114,9 +114,15 @@ function convertSingle(raw: string, options: NumberToWordsOptions): string { if (trimmed === '') return ''; const negative = trimmed.startsWith('-'); - const unsigned = negative ? trimmed.slice(1) : trimmed; + let unsigned = negative ? trimmed.slice(1) : trimmed; - // Validate: optional integer part, optional decimal part + // Normalize edge-case decimal forms: a trailing dot ("5." -> "5") or a + // leading dot (".25" -> "0.25"). Order matters: strip the trailing dot first + // so a lone "." becomes "" and is rejected by the validation below. + if (unsigned.endsWith('.')) unsigned = unsigned.slice(0, -1); + if (unsigned.startsWith('.')) unsigned = `0${unsigned}`; + + // Validate: integer part required, optional decimal part if (!/^\d+(\.\d+)?$/.test(unsigned)) return ''; const [intPart, fracPart] = unsigned.split('.');