Convert digits into words with JavaScript

后端 未结 27 1545
我寻月下人不归
我寻月下人不归 2020-11-22 15:08

I am making a code which converts the given amount into words, heres is what I have got after googling. But I think its a little lengthy code to achieve a simple task. Two R

27条回答
  •  半阙折子戏
    2020-11-22 15:55

    I've just written paisa.js to do this, and it handles lakhs and crores correctly as well, can check it out. The core looks a bit like this:

    const regulars = [
      {
        1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'
      },
      {
        2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety'
      }
    ]
    
    const exceptions = {
      10: 'ten',
      11: 'eleven',
      12: 'twelve',
      13: 'thirteen',
      14: 'fourteen',
      15: 'fifteen',
      16: 'sixteen',
      17: 'seventeen',
      18: 'eighteen',
      19: 'nineteen'
    }
    
    const partInWords = (part) => {
      if (parseInt(part) === 0) return
      const digits = part.split('')
      const words = []
      if (digits.length === 3) {
        words.push([regulars[0][digits.shift()], 'hundred'].join(' '))
      }
      if (exceptions[digits.join('')]) {
        words.push(exceptions[digits.join('')])
      } else {
        words.push(digits.reverse().reduce((memo, el, i) => {
          memo.unshift(regulars[i][el])
          return memo
        }, []).filter(w => w).join(' '))
      }
      return words.filter(w => w.trim().length).join(' and ')
    }
    

提交回复
热议问题