Skip to content

Instantly share code, notes, and snippets.

@farithadnan
Last active October 30, 2024 05:14
Show Gist options
  • Save farithadnan/7d2b97f50587e3c552c4fdedfe8bed35 to your computer and use it in GitHub Desktop.
Save farithadnan/7d2b97f50587e3c552c4fdedfe8bed35 to your computer and use it in GitHub Desktop.
Number to English Function
function numToEng(num) {
if (num < 1 || num > 999) {
throw new Error("Number must be between 1 and 999");
}
let ones = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
let teens = ["eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
let tens = ["ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
if (num < 10) return ones[num - 1];
if (num < 20) return teens[num - 11];
if (num < 100) {
return tens[Math.floor(num / 10) - 1] + (num % 10 ? " " + ones[(num % 10) - 1] : "");
}
return ones[Math.floor(num / 100) - 1] + " hundred" + (num % 100 ? " " + numToEng(num % 100) : "");
}
@farithadnan
Copy link
Author

Instruction:
Write a function that accepts a positive integer between 0 and 999 inclusive and returns a string representation of that integer written in English.

Notes

  • There are no hyphens used (e.g. "thirty five" not "thirty-five").
  • The word "and" is not used (e.g. "one hundred one" not "one hundred and one").

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment