Created
October 21, 2022 02:32
-
-
Save TuanMinPay/1914898789059f5701429e6310ae0ca3 to your computer and use it in GitHub Desktop.
Integer to English Words
This file contains 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
var numberToWords = function (num) { | |
if (num === 0) return 'Zero'; | |
const units = ['', '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 thousands = ['', 'Thousand', 'Million', 'Billion']; | |
const helper = (num) => { | |
if (num === 0) return ''; | |
if (num < 20) return `${units[num]} `; | |
if (num < 100) return `${tens[parseInt(num / 10)]} ${helper(num % 10)}`; | |
return `${units[parseInt(num / 100)]} Hundred ${helper(num % 100)}`; | |
} | |
let result = ''; | |
for (let i = 0; i < thousands.length; i++) { | |
if (num % 1000 !== 0) result = `${helper(num % 1000)}${thousands[i]} ${result}`; | |
num = parseInt(num / 1000); | |
} | |
return result.trim(); | |
}; | |
console.log(numberToWords(2147483647)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Convert a non-negative integer
num
to its English words representation.