Last active
October 30, 2024 05:14
-
-
Save farithadnan/7d2b97f50587e3c552c4fdedfe8bed35 to your computer and use it in GitHub Desktop.
Number to English Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) : ""); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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