UNPKG

word-number-converter

Version:

A simple JavaScript library to convert numbers to words and words to numbers. Works in both Node.js and browser environments.

37 lines (33 loc) 1.08 kB
const WORDS_TO_NUM = { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19, twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90, }; const MULTIPLIERS = { hundred: 100, thousand: 1000, lacs: 100000, million: 1000000, billion: 1000000000 }; export function toNumber(str) { const words = str.toLowerCase().replace(/-/, ' ').split(/\s+/); let result = 0; let current = 0; for (const word of words) { if (word === 'and') continue; if (WORDS_TO_NUM[word] !== undefined) { current += WORDS_TO_NUM[word]; } else if (MULTIPLIERS[word]) { current *= MULTIPLIERS[word]; if (MULTIPLIERS[word] >= 1000) { result += current; current = 0; } } } return result + current; }