JavaScript编号为单词 [英] JavaScript numbers to Words

查看:103
本文介绍了JavaScript编号为单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数字转换为英语单词,例如 1234 将成为:一千二百三十四



My Tactic是这样的:




  • 将数字分成三个并将它们放在数组上( finlOutPut ),从右到左。


  • 转换每个组(<$ c中的每个单元格$ c> finlOutPut array)一个单词的三位数(这就是 triConvert 函数的作用)。如果所有三位数都为零,则将它们转换为dontAddBigSuffix


  • 从右到左,添加千,百万,亿等。如果 finlOutPut 单元格等于dontAddBigSufix(因为它只是零),请不要添加单词和集合单元格(无)。




它似乎工作得很好,但我遇到了一些问题,如19000000 9 ,转换为:一亿九千万。不知何故,当有几个零时它会忘记最后的数字。



我做错了什么?这个bug在哪里?为什么它不能很好地工作?

 









id =number
size =70
onkeyup =update();
/ *此代码防止非数字字母* /
onkeydown =return(event.ctrlKey || event.altKey
||(47 ||(95 ||(event.keyCode == 8)||(event.keyCode == 9)
||(event.keyCode> 34 && event.keyCode <40)
||(event.keyCode == 46))/>


这里打印的数字





解决方案

当有一个前导零位数时,JavaScript正在将3个数字组解析为八进制数。当三位数组全部为零时,无论基数是八进制还是十进制,结果都是相同的。



但是当你给JavaScript'009'(或'008)时'),这是一个无效的八进制数,所以你得到零回。



如果你经历了从190,000,001到190,000,010的整组数字,你会看到JavaScript跳过'...,008'和'...,009',但为'...,010'发出'8'。这就是'Eureka!'时刻。



更改:

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

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

代码也会在每个非零组后添加逗号,所以我玩了有了它,找到了添加逗号的正确位置。



旧:

  for(b = finlOutPut.length  -  1; b> = 0; b--){
if(finlOutPut [b]!=dontAddBigSufix){
finlOutPut [b] = finlOutPut [b] + bigNumArry [bigScalCntr] +',';
bigScalCntr ++;
}
else {
//将finlOP [b]中的字符串从dontAddBigSufix替换为空字符串。
finlOutPut [b] ='';
bigScalCntr ++; //推进计数器
}
}

//将输出Arry转换为更多可打印字符串
for(n = 0; n< finlOutPut.length; n ++){
output + = finlOutPut [n];
}

新:

  for(b = finlOutPut.length  -  1; b> = 0; b--){
if(finlOutPut [b]!=dontAddBigSufix){
finlOutPut [b] = finlOutPut [b] + bigNumArry [bigScalCntr]; //<<<
bigScalCntr ++;
}
else {
//将finlOP [b]中的字符串从dontAddBigSufix替换为空字符串。
finlOutPut [b] ='';
bigScalCntr ++; //推进计数器
}
}

//将输出Arry转换为更多可打印字符串
var nonzero = false; //<<<
for(n = 0; n< finlOutPut.length; n ++){
if(finlOutPut [n]!=''){//<<<
if(非零)输出+ =','; //<<<
非零=真; //<<<
} //<<<
输出+ = finlOutPut [n];
}


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

My Tactic goes like this:

  • Separate the digits to three and put them on Array (finlOutPut), from right to left.

  • Convert each group (each cell in the finlOutPut array) of three digits to a word (this what the triConvert function does). If all the three digits are zero convert them to "dontAddBigSuffix"

  • From Right to left, add thousand, million, billion, etc. If the finlOutPut cell equals "dontAddBigSufix" (because it was only zeroes), don't add the word and set the cell to " " (nothing).

It seems to work pretty well, but I've got some problems with numbers like 190000009, converted to: "one hundred ninety million". Somehow it "forgets" the last numbers when there are a few zeros.

What did I do wrong? Where is the bug? Why does it not work perfectly?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

<script type="text/javascript">
function update(){
    var bigNumArry = new Array('', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion');

    var output = '';
    var numString =   document.getElementById('number').value;
    var finlOutPut = new Array();

    if (numString == '0') {
        document.getElementById('container').innerHTML = 'Zero';
        return;
    }

    if (numString == 0) {
        document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
        return;
    }

    var i = numString.length;
    i = i - 1;

    //cut the number to grups of three digits and add them to the Arry
    while (numString.length > 3) {
        var triDig = new Array(3);
        triDig[2] = numString.charAt(numString.length - 1);
        triDig[1] = numString.charAt(numString.length - 2);
        triDig[0] = numString.charAt(numString.length - 3);

        var varToAdd = triDig[0] + triDig[1] + triDig[2];
        finlOutPut.push(varToAdd);
        i--;
        numString = numString.substring(0, numString.length - 3);
    }
    finlOutPut.push(numString);
    finlOutPut.reverse();

    //conver each grup of three digits to english word
    //if all digits are zero the triConvert
    //function return the string "dontAddBigSufix"
    for (j = 0; j < finlOutPut.length; j++) {
        finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
    }

    var bigScalCntr = 0; //this int mark the million billion trillion... Arry

    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<finlOutPut.length; n++){
            output +=finlOutPut[n];
        }

    document.getElementById('container').innerHTML = output;//print the output
}

//simple function to convert from numbers to words from 1 to 999
function triConvert(num){
    var ones = new Array('', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
    var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety');
    var hundred = ' hundred';
    var output = '';
    var numString = num.toString();

    if (num == 0) {
        return 'dontAddBigSufix';
    }
    //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;
}   
</script>

</head>
<body>

<input type="text"
    id="number"
    size="70"
    onkeyup="update();"
    /*this code prevent non numeric letters*/ 
    onkeydown="return (event.ctrlKey || event.altKey 
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false) 
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9) 
                    || (event.keyCode>34 && event.keyCode<40) 
                    || (event.keyCode==46) )"/>
                    <br/>
<div id="container">Here The Numbers Printed</div>
</body>
</html>

解决方案

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<finlOutPut.length; n++){
        output +=finlOutPut[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<finlOutPut.length; n++){
        if (finlOutPut[n] != ' ') { // <<<
            if (nonzero) output += ' , '; // <<<
            nonzero = true; // <<<
        } // <<<
        output +=finlOutPut[n];
    }

这篇关于JavaScript编号为单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆