convert number to words javascript in javascript

index.tsx
function numToWords(num) {
  const ones = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
  const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
  const teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
  const suffixes = ['', 'thousand', 'million', 'billion'];

  let words = [];

  if (num === 0) {
    words.push('zero');
  } else {
    if (num < 0) {
      words.push('minus');
      num = -num;
    }

    let groups = [];
    while (num > 0) {
      groups.push(num % 1000);
      num = parseInt(num / 1000, 10);
    }

    if (groups.length > suffixes.length) {
      return 'Too big!';
    } else {
      for (let i = 0; i < groups.length; i++) {
        let groupWords = [];
        let group = groups[i];
        if (group > 99) {
          groupWords.push(ones[Math.floor(group / 100)] + ' hundred');
          group = group % 100;
        }
        if (group > 9 && group < 20) {
          groupWords.push(teens[group - 10]);
        } else {
          if (group > 19) {
            groupWords.push(tens[Math.floor(group / 10)]);
            group = group % 10;
          }
          if (group > 0) {
            groupWords.push(ones[group]);
          }
        }
        if (groupWords.length > 0) {
          groupWords.push(suffixes[i]);
        }
        words = groupWords.concat(words);
      }
    }
  }

  return words.join(' ');
}
1501 chars
54 lines

This function will convert a number into words using American English naming conventions. It can handle numbers from -999,999,999 to 999,999,999. Simply pass your number as an argument to the function and it will return the corresponding words.

gistlibby LogSnag