Created
April 28, 2022 06:04
-
-
Save vella-nicholas/ac4c37892ff2e827ad61782cd011f803 to your computer and use it in GitHub Desktop.
Converts and integer to its string equivalent (EN)
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
const numberToWords = function(num) { | |
let result = toHundreds(num % 1000); | |
const bigNumbers = ["Thousand", "Million", "Billion"]; | |
for (let i = 0; i < 3; ++i) { | |
num = Math.trunc(num / 1000); | |
result = num % 1000 !== 0 ? [toHundreds(num % 1000), bigNumbers[i], result].filter(Boolean).join(" ") : result; | |
} | |
return result.length === 0 ? "Zero" : result; | |
} | |
function toHundreds(num) { | |
const numbers = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", | |
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]; | |
const tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]; | |
const result = Array(3).fill(""); | |
let a = Math.trunc(num / 100), b = num % 100, c = num % 10; | |
result[0] = a > 0 && `${numbers[a]} Hundred`; | |
result[1] = b < 20 ? numbers[b] : tens[Math.trunc(b / 10)] | |
result[2] = b >= 20 && `${numbers[c]}`; | |
return result.filter(Boolean).join(" "); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Taken from Top 10 Algorithms to Improve your JavaScript Skills