JavaScript numbers to Words

前端 未结 24 1500
死守一世寂寞
死守一世寂寞 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条回答
  •  -上瘾入骨i
    2020-11-22 15:03

    I would like to point out that the original logic fails for values between x11-x19, where x >= 1. For example, 118 returns "one hundred eight". This is because these numbers are processed by the following code in triConvert():

    //100 and more
    if (numString.length == 3) {
        output = ones[parseInt(numString.charAt(0))] + hundred;
        output += tens[parseInt(numString.charAt(1))];
        output += ones[parseInt(numString.charAt(2))];
        return output;
    }
    

    here, the character representing the tens digit is used to index the tens[] array, which has an empty string at index [1], so 118 become 108 in effect.

    It might be better to deal with the hundreds (if any first), then run the ones and tens through the same logic. Instead of:

    //the case of 10, 11, 12 ,13, .... 19 
    if (num < 20) {
        output = ones[num];
        return output;
    }
    
    //100 and more
    if (numString.length == 3) {
        output = ones[parseInt(numString.charAt(0))] + hundred;
        output += tens[parseInt(numString.charAt(1))];
        output += ones[parseInt(numString.charAt(2))];
        return output;
    }
    
    output += tens[parseInt(numString.charAt(0))];
    output += ones[parseInt(numString.charAt(1))];
    
    return output;
    

    I would suggest:

    // 100 and more
    if ( numString.length == 3 ) 
     {
       output  = hundreds[ parseInt( numString.charAt(0) ) ] + hundred ;
       num = num % 100 ;
       numString = num.toString() ;
     }
    
    if ( num < 20 )  
     {
       output += ones[num] ;
     }
    else 
     { // 20-99 
       output += tens[ parseInt( numString.charAt(0) ) ] ;
       output += '-' + ones[ parseInt( numString.charAt(1) ) ] ;  
     }
    
     return output;
    

    It seems to me that the suggested code is both shorter and clearer, but I might be biased ;-)

提交回复
热议问题