Merge pull request #2 from ParasxAgarwal/feat/number-to-words-decimals

fix: accept leading/trailing decimal points in number-to-words
This commit is contained in:
PARAS AGARWAL authored and GitHub committed 2026-07-29 08:43:03 +05:30
commit 339ac10bb8
2 files changed
+24 -2

No files matched your search

@@ -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('');
});
});
@@ -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('.');