JSFiddle - React, Tailwind, and code Playground

by Abdul Ahmad

JavaScript

console.log(convertNumberToWords('745.48'));

var hasPeriod = false;


function numberToWords() {
  return {
    '9': 'nine',
    '8': 'eight',
    '7': 'seven',
    '6': 'six',
    '5': 'five',
    '0': 'zero',
  };
}

function tensToWords() {
  return {
    '4': 'fourty',
  };
}


function convertNumberToWords(number) {
  const parts = getSplitNumber(number);
  const wordsForWhole = getWordsForNumber(parts.whole);
  const wordsForDecimal = getWordsForDecimal(parts.decimal);

	if (!wordsForDecimal) return wordsForWhole;
  
  return `${wordsForWhole} and ${wordsForDecimal}`;
}

function getSplitNumber(number) {
  let splitChar = ',';
  hasPeriod = number.includes('.');
  if (hasPeriod) splitChar =  '.';
  const split = number.split(splitChar);

  return {
    whole: split[0],
    decimal: split[1],
  };
}

function getWordsForNumber(num) {
  let actualNumber = num;
  const hasCommas = actualNumber.includes(',');
  if (hasCommas) actualNumber = getWholeWithoutCommas(whole);
  const length = actualNumber.length;
  let numberInWords = '';

  // - since we're starting from right, we start with singles,
  //   then tens, then hundreds, etc...
  let placeMap = {
    '2': getSingles,
    '1': getTens,
    '0': getHundreds,
  }

  for (let i = length - 1; i > -1; i--) {
    const number = actualNumber[i];
    const words = placeMap[i](number);
    numberInWords = `${words} ${numberInWords}`;
  }

  return numberInWords;
}

function getWordsForDecimal(num) {
  let numberInWords = '';

  // - since we're starting from right, we start with singles,
  //   then tens, then hundreds, etc...
  let placeMap = {
    '1': getSingles,
    '0': getTens,
  }
  
  let words = [];

  for (let i = 0; i < num.length; i++) {
    const number = num[i];
    const word = placeMap[i](number);
    words.push(word);
  }
  
  if (!words[0] && words[1] === 'zero') return undefined;
  if (!words[0]) return words[1];

  return words.join(' ');
}

function getHundreds(number) {
  return...