DEV Community

Discussion on: Daily Challenge #19 - Turn numbers into words

Collapse
 
alvaromontoro profile image
Alvaro Montoro

JavaScript

const letterifyNumber = number => {

  const singulars = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
  const decens = ["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
  const teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "egighteen", "nineteen"];
  const units = ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sixtillion", "septillion"];
  const blocks = number.toString().split('').reverse().join('').match(/.{1,3}/g);

  let numberString = "";
  for (let x = 0; x < blocks.length; x++) {
    let sectionString = "";
    if (parseInt(blocks[x]) !== 0) {
      if (blocks[x].length > 2 && blocks[x][2] !== "0") {
        sectionString += `${singulars[blocks[x][2]]} hundred `
      }
      if (blocks[x].length > 1) {
        if (blocks[x][1] === "1") {
          sectionString += `${teens[blocks[x][0]]} `
        } else {
          sectionString += `${decens[blocks[x][1]]} `;
        }
      }
      if (blocks[x][1] !== "1") {
        sectionString += `${singulars[blocks[x][0]]} `
      }
      sectionString += `${units[x]} `
      numberString = sectionString + numberString;
    }
  }

  return numberString;
}

Live demo on CodePen.