UNPKG

everyutil

Version:

A comprehensive library of lightweight, reusable utility functions for JavaScript and TypeScript, designed to streamline common programming tasks such as string manipulation, array processing, date handling, and more.

30 lines (29 loc) 1.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.numberToWords = void 0; /** * Converts a number to its English words representation (simple, up to millions). * For example, numberToWords(123) returns "one hundred twenty-three". * @author @dailker * @param {number} n - The number to convert. * @returns {string} The English words representation of the number. */ const ones = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]; const teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]; const tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; function numberToWords(n) { if (n < 0) return "minus " + numberToWords(-n); if (n < 10) return ones[n]; if (n < 20) return teens[n - 10]; if (n < 100) return tens[Math.floor(n / 10)] + (n % 10 ? "-" + ones[n % 10] : ""); if (n < 1000) return ones[Math.floor(n / 100)] + " hundred" + (n % 100 ? " " + numberToWords(n % 100) : ""); if (n < 1000000) return numberToWords(Math.floor(n / 1000)) + " thousand" + (n % 1000 ? " " + numberToWords(n % 1000) : ""); return n.toString(); } exports.numberToWords = numberToWords;