Number to English

Given a number between 0 and 9999, print the number in English. For example, for the number 123, print ‘one hundred twenty three’.

const ones = {
  0: 'zero',
  1: 'one',
  2: 'two',
  3: 'three',
  4: 'four',
  5: 'five',
  6: 'six',
  7: 'seven',
  8: 'eight',
  9: 'nine'
}

const tens = {
  9: 'ninety',
  8: 'eighty',
  7: 'seventy',
  6: 'sixty',
  5: 'fifty',
  4: 'forty',
  3: 'thirty',
  2: 'twenty',
  1: 'ten'
}

let teens = {
  19: 'nineteen',
  18: 'eighteen',
  17: 'seventeen',
  16: 'sixteen',
  15: 'fifteen',
  14: 'fourteen',
  13: 'thirteen',
  12: 'twelve',
  11: 'eleven',
  10: 'ten'
}

let number = 123
number = 113
number = 4103
number = 9999

let digitIndex = 0
let remainder = 0
let firstDigit = 0
let sentence = ''


while (number > 0) {
  remainder = number % 10
  number = parseInt(number / 10)
  digitIndex += 1

  if (digitIndex === 1) { // 1st digit
    firstDigit = remainder
  }
  else if (digitIndex === 2) { // 2nd digit
    if (remainder >= 2) { // 20 and up
      sentence = tens[remainder] + ' ' + sentence

      if (firstDigit != 0) {
        sentence = sentence + ones[firstDigit]
      }
    }
    else if (remainder === 1) { // teens or ten
      const total = 10 + firstDigit
      sentence = teens[total] + ' ' + sentence
    }
    else { // ones
      if (firstDigit != 0) {
        sentence = ones[firstDigit] + ' ' + sentence
      }
    }
  }
  else if (digitIndex === 3) { // 3rd digit
    sentence = ones[remainder] + ' hundred ' + sentence
  }
  else if (digitIndex === 4) { // 4th digit
    sentence = ones[remainder] + ' thousand ' + sentence
  }
}

console.log(sentence)

 

Scroll to top