JavaScript numbers to Words

前端 未结 24 1511
死守一世寂寞
死守一世寂寞 2020-11-22 14:39

I\'m trying to convert numbers into english words, for example 1234 would become: \"one thousand two hundred thirty four\".

My Tact

24条回答
  •  没有蜡笔的小新
    2020-11-22 14:46

    I've modified the posting from Šime Vidas - http://jsfiddle.net/j5kdG/ To include dollars, cents, commas and "and" in the appropriate places. There's an optional ending if it requires "zero cents" or no mention of cents if 0.

    This function structure did my head in a bit but I learned heaps. Thanks Sime.

    Someone might find a better way of processing this.

    Code:

    var str='';
    var str2='';
    var str3 =[];
    
    function convertNum(inp,end){
        str2='';
        str3 = [];
        var NUMBER2TEXT = {
        ones: ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'],
        tens: ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'],
        sep: ['', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion', ' sextillion']
    };
    (function( ones, tens, sep ) {
       var vals = inp.split("."),val,pos,postsep=' ';
       for (p in vals){
          val = vals[p], arr = [], str = '', i = 0;
          if ( val.length === 0 ) {return 'No value';}
          val = parseInt( (p==1 && val.length===1 )?val*10:val, 10 );
          if ( isNaN( val ) || p>=2) {return 'Invalid value'; }
          while ( val ) {
            arr.push( val % 1000 );
            val = parseInt( val / 1000, 10 );   
          }
          pos = arr.length;
          function trimx (strx) {
                    return strx.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
                }
            function seps(sepi,i){
                    var s = str3.length
                    if (str3[s-1][0]){
                        if (str3[s-2][1] === str3[s-1][0]){
                            str = str.replace(str3[s-2][1],'')
                        }
                    }
                    var temp = str.split(sep[i-2]);
                    if (temp.length > 1){
                        if (trimx(temp[0]) ==='' && temp[1].length > 1 ){
                            str = temp[1];
                            } 
                        }
                    return sepi + str ;
            }
          while ( arr.length  ) {
            str = (function( a ) {
                var x = Math.floor( a / 100 ),
                    y = Math.floor( a / 10 ) % 10,
                    z = a % 10;
                    postsep = (arr.length != 0)?', ' : ' ' ;
                    if ((x+y+z) === 0){
                        postsep = ' '
                    }else{ 
                        if (arr.length == pos-1 && x===0 && pos > 1 ){
                            postsep = ' and ' 
                        } 
                    }
                   str3.push([trimx(str)+"",trimx(sep[i])+""]);
                    return  (postsep)+( x > 0 ? ones[x] + ' hundred ' + (( x == 0 && y >= 0 || z >0 )?' and ':' ') : ' ' ) +                  
                       ( y >= 2 ? tens[y] + ((z===0)?' ':'-') + ones[z] : ones[10*y + z] ); 
            })( arr.shift() ) +seps( sep[i++] ,i ) ;             
          }
          if (p==0){ str2 += str + ' dollars'}
          if (p==1 && !end){str2 += (str!='')?' and '+ str + ' cents':'' } 
          if (p==1 && end ){str2 += ' and ' + ((str==='')?'zero':str) + ' cents '} 
       }
    })( NUMBER2TEXT.ones , NUMBER2TEXT.tens , NUMBER2TEXT.sep );
    

提交回复
热议问题