Skip to content

Instantly share code, notes, and snippets.

@SurendraTamang
Created March 12, 2024 02:06
Show Gist options
  • Save SurendraTamang/4da1cbc0b687988effd4048b8048cecb to your computer and use it in GitHub Desktop.
Save SurendraTamang/4da1cbc0b687988effd4048b8048cecb to your computer and use it in GitHub Desktop.
Number to words
function numberToWords(num) {
if (num === 0) return "zero";
const underTwenty = ["", "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 scales = ["", "thousand", "million", "billion", "trillion", "quadrillion"]; // Extend as needed
const toWords = (n) => {
if (n < 20) return underTwenty[n];
if (n < 100) return tens[Math.floor(n / 10)] + (n % 10 ? " " + underTwenty[n % 10] : "");
if (n < 1000) return underTwenty[Math.floor(n / 100)] + " hundred" + (n % 100 ? " " + toWords(n % 100) : "");
};
if (typeof num !== "number") num = Number(num);
if (isNaN(num)) return "Not a number";
let index = 0;
const parts = [];
while (num > 0) {
const part = num % 1000;
if (part > 0) {
parts.unshift(toWords(part) + (scales[index] ? " " + scales[index] : ""));
}
num = Math.floor(num / 1000);
index++;
}
return parts.join(" ").trim();
}
console.log(numberToWords(12345678901234)); // Example usage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment