JavaScript numbers to Words

前端 未结 24 1571
死守一世寂寞
死守一世寂寞 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:45

    JavaScript is parsing the group of 3 numbers as an octal number when there's a leading zero digit. When the group of three digits is all zeros, the result is the same whether the base is octal or decimal.

    But when you give JavaScript '009' (or '008'), that's an invalid octal number, so you get zero back.

    If you had gone through the whole set of numbers from 190,000,001 to 190,000,010 you'd hav seen JavaScript skip '...,008' and '...,009' but emit 'eight' for '...,010'. That's the 'Eureka!' moment.

    Change:

    for (j = 0; j < finlOutPut.length; j++) {
        finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
    }
    

    to

    for (j = 0; j < finlOutPut.length; j++) {
        finlOutPut[j] = triConvert(parseInt(finlOutPut[j],10));
    }
    

    Code also kept on adding commas after every non-zero group, so I played with it and found the right spot to add the comma.

    Old:

    for (b = finlOutPut.length - 1; b >= 0; b--) {
        if (finlOutPut[b] != "dontAddBigSufix") {
            finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
            bigScalCntr++;
        }
        else {
            //replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
            finlOutPut[b] = ' ';
            bigScalCntr++; //advance the counter  
        }
    }
    
        //convert The output Arry to , more printable string 
        for(n = 0; n

    New:

    for (b = finlOutPut.length - 1; b >= 0; b--) {
        if (finlOutPut[b] != "dontAddBigSufix") {
            finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr]; // <<<
            bigScalCntr++;
        }
        else {
            //replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
            finlOutPut[b] = ' ';
            bigScalCntr++; //advance the counter  
        }
    }
    
        //convert The output Arry to , more printable string 
        var nonzero = false; // <<<
        for(n = 0; n

提交回复
热议问题