Skip to content

Instantly share code, notes, and snippets.

@nojvek nojvek/words2num.js
Created Aug 29, 2019

Embed
What would you like to do?
Words to Num
const wordsToNumMap = {
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,
fourty: 40,
fifty: 50,
sixty: 60,
seventy: 70,
eighty: 80,
ninety: 90,
hundred: 100,
thousand: 1e3,
million: 1e6,
billion: 1e9,
trillion: 1e12,
};
function wordsToNum(str) {
console.info(str);
const nums = str
.trim()
.replace(/[^a-zA-Z ]/g, ``)
.split(/\s+/)
.map(word => wordsToNumMap[word]);
let result = 0;
let segmentResult = 0;
for (const num of nums) {
if (num < 100) {
segmentResult += num;
} else if (num === 100) {
segmentResult *= num;
} else {
result += segmentResult * num;
segmentResult = 0;
}
}
result += segmentResult;
console.info(result.toLocaleString());
}
wordsToNum(`
one billion,
two hundred thirty four million,
five hundred sixty seven thousand,
eight hundred ninety
`);
wordsToNum(`one billion six hundred thousand fourty four`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.