Convert digits into words with JavaScript

后端 未结 27 1456
我寻月下人不归
我寻月下人不归 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 15:36

    while this system does use a for loop, It uses US english and is fast, accurate, and expandable(you can add infinite values to the "th" var and they will be included).

    This function grabs the 3 groups of numbers backwards so it can get the number groups where a , would normally separate them in the numeric form. Then each group of three numbers is added to an array with the word form of just the 3 numbers(ex: one hundred twenty three). It then takes that new array list, and reverses it again, while adding the th var of the same index to the end of the string.

    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 ','forty ','fifty ', 'sixty ','seventy ','eighty ','ninety ', 'hundred '];
    var th = ['', 'thousand ','million ','billion ', 'trillion '];
    
    function numberToWord(number){
      var text = "";
      var size = number.length;
    
      var textList = [];
      var textListCount = 0;
    
      //get each 3 digit numbers
      for(var i = number.length-1; i >= 0; i -= 3){
        //get 3 digit group
        var num = 0;
        if(number[(i-2)]){num += number[(i-2)];}
        if(number[(i-1)]){num += number[(i-1)];}
        if(number[i]){num += number[i];}
    
        //remove any extra 0's from begining of number
        num = Math.floor(num).toString();
    
        if(num.length == 1 || num < 20){
          //if one digit or less than 20
          textList[textListCount] = ones[num];
        }else if(num.length == 2){
          //if 2 digits and greater than 20
          textList[textListCount] = tens[num[0]]+ones[num[1]];
        }else if(num.length == 3){
          //if 3 digits
          textList[textListCount] = ones[num[0]]+tens[10]+tens[num[1]]+ones[num[2]];
        }
    
        textListCount++;
    
      }
    
      //add the list of 3 digit groups to the string
      for(var i = textList.length-1; i >= 0; i--){
        if(textList[i] !== ''){text += textList[i]+th[i];} //skip if the number was 0
      }
    
      return text;
    }
    

提交回复
热议问题