Skip to content

Instantly share code, notes, and snippets.

@TuanMinPay
Created October 21, 2022 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TuanMinPay/1914898789059f5701429e6310ae0ca3 to your computer and use it in GitHub Desktop.
Save TuanMinPay/1914898789059f5701429e6310ae0ca3 to your computer and use it in GitHub Desktop.
Integer to English Words
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));
@TuanMinPay
Copy link
Author

Convert a non-negative integer num to its English words representation.

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