Skip to content

Instantly share code, notes, and snippets.

@nojvek
Created August 29, 2019 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nojvek/1f7251a51e92a4239b94eb123c17d13c to your computer and use it in GitHub Desktop.
Save nojvek/1f7251a51e92a4239b94eb123c17d13c to your computer and use it in GitHub Desktop.
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