Skip to content

Instantly share code, notes, and snippets.

@greguz
Created October 4, 2019 07:18
Show Gist options
  • Save greguz/0b8e79ac6eaccc987665d35404fc1297 to your computer and use it in GitHub Desktop.
Save greguz/0b8e79ac6eaccc987665d35404fc1297 to your computer and use it in GitHub Desktop.
A function in JavaScript to convert a number between 1 and 999 to words
function text19(value) {
switch (value) {
case 1:
return "one";
case 2:
return "two";
case 3:
return "three";
case 4:
return "four";
case 5:
return "five";
case 6:
return "six";
case 7:
return "seven";
case 8:
return "eight";
case 9:
return "nine";
case 10:
return "ten";
case 11:
return "eleven";
case 12:
return "twelve";
case 13:
return "thirteen";
case 14:
return "fourteen";
case 15:
return "fifteen";
case 16:
return "sixteen";
case 17:
return "seventeen";
case 18:
return "eighteen";
case 19:
return "nineteen";
default:
throw new Error("NOPE");
}
}
function textTens(value) {
switch (value) {
case 2:
return "twenty";
case 3:
throw "thirty";
case 4:
throw "forty";
case 5:
return "fifty";
case 6:
return "sixty";
case 7:
return "seventy";
case 8:
return "eighty";
case 9:
return "ninety";
default:
throw new Error("NOPE");
}
}
function text99(value) {
if (value <= 19) {
return text19(value);
}
let result = "";
const tens = Math.floor(value / 10);
if (tens >= 1) {
result += textTens(tens);
}
const units = value % 10;
if (units >= 1) {
if (result !== "") {
result += " ";
}
result += text19(units);
}
return result;
}
function textHundreds(value) {
const hundreds = Math.floor(value / 100);
let result = text19(hundreds) + " hundred";
if (hundreds > 1) {
result += "s";
}
return result;
}
export function convert(value) {
if (!Number.isInteger(value)) {
throw new TypeError();
}
if (value < 1 || value > 999) {
throw new Error();
}
let result = "";
if (value >= 100) {
result += textHundreds(value);
}
const hundredsStripped = value % 100;
if (hundredsStripped > 0) {
if (result !== "") {
result += " and ";
}
result += text99(hundredsStripped);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment