Convert digits into words with JavaScript

后端 未结 27 1572
我寻月下人不归
我寻月下人不归 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:40

    This is in response to @LordZardeck's comment to @naomik's excellent answer above. Sorry, I would've commented directly but I've never posted before so I don't have the privilege to do so, so I am posting here instead.

    Anyhow, I just happened to translate the ES5 version to a more readable form this past weekend so I'm sharing it here. This should be faithful to the original (including the recent edit) and I hope the naming is clear and accurate.

    function int_to_words(int) {
      if (int === 0) return 'zero';
    
      var ONES  = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
      var TENS  = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
      var SCALE = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];
    
      // Return string of first three digits, padded with zeros if needed
      function get_first(str) {
        return ('000' + str).substr(-3);
      }
    
      // Return string of digits with first three digits chopped off
      function get_rest(str) {
        return str.substr(0, str.length - 3);
      }
    
      // Return string of triplet convereted to words
      function triplet_to_words(_3rd, _2nd, _1st) {
        return (_3rd == '0' ? '' : ONES[_3rd] + ' hundred ') + (_1st == '0' ? TENS[_2nd] : TENS[_2nd] && TENS[_2nd] + '-' || '') + (ONES[_2nd + _1st] || ONES[_1st]);
      }
    
      // Add to words, triplet words with scale word
      function add_to_words(words, triplet_words, scale_word) {
        return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + words : words;
      }
    
      function iter(words, i, first, rest) {
        if (first == '000' && rest.length === 0) return words;
        return iter(add_to_words(words, triplet_to_words(first[0], first[1], first[2]), SCALE[i]), ++i, get_first(rest), get_rest(rest));
      }
    
      return iter('', 0, get_first(String(int)), get_rest(String(int)));
    }
    

提交回复
热议问题