Skip to content

Instantly share code, notes, and snippets.

@rock3m
Created December 16, 2020 02:31
Show Gist options
  • Save rock3m/86b0b1e040063802d2291ee7349659e8 to your computer and use it in GitHub Desktop.
Save rock3m/86b0b1e040063802d2291ee7349659e8 to your computer and use it in GitHub Desktop.
// Create a dictionary for all the unique words (one … ten, eleven … nineteen, twenty, thirty, forty, … ninty)
var WORD_DICT = {
0: "",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five",
6: "six",
7: "seven",
8: "eight",
9: "nine",
10: "ten",
11: "eleven",
12: "twelve",
13: "thirteen",
14: "fourteen",
15: "fifteen",
16: "sixteen",
17: "seventeen",
18: "eighteen",
19: "nineteen",
20: "twenty",
30: "thirty",
40: "forty",
50: "fifty",
60: "sixty",
70: "seventy",
80: "eighty",
90: "ninty",
100: "hundred"
};
function convertNumberToWords(inputNumber) {
var outputWords = []
// Check the boundaries: <1 and > 999
if (!inputNumber || inputNumber < 1 || inputNumber > 999) {
throw new Error("Invalid input");
}
// Check simple unique words: <20
if (inputNumber < 20) {
return WORD_DICT[inputNumber];
}
var hundredsPosition = Math.floor(inputNumber / 100);
var tensPosition = hundredsPosition % 100;
var onesPostion = hundredsPosition % 10;
// Check hundreds: if hundreds, look up the word in dictionary, plus "<space>hundred"; otherwise, do nothing
if (hundredsPosition > 0) {
outputWords.push(WORD_DICT[hundredsPosition], WORD_DICT[100]);
}
// Check tens: if tens, look up the word in dictionary; otherwise, do nothing
if (tensPosition >= 2) {
outputWords.push(WORD_DICT[10 * tensPosition]);
// Check ones: if ones, look up the word in dictionary; otherwise, do nothing
if (onesPostion) {
outputWords.push(WORD_DICT[onesPostion])
}
} else {
outputWords.push(WORD_DICT[inputNumber - hundredsPosition * 100]);
}
// Put all the words together
return outputWords.join(" ");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment