JavaScript numbers to Words

前端 未结 24 1188
死守一世寂寞
死守一世寂寞 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<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];
        }
    
    0 讨论(0)
  • 2020-11-22 14:45

    Try this,convert number to words

    function convert(number) {
    
        if (number < 0) {
    
            console.log("Number Must be greater than zero = " + number);
            return "";
        }
        if (number > 100000000000000000000) {
            console.log("Number is out of range = " + number);
            return "";
        }
        if (!is_numeric(number)) {
            console.log("Not a number = " + number);
            return "";
        }
    
        var quintillion = Math.floor(number / 1000000000000000000); /* quintillion */
        number -= quintillion * 1000000000000000000;
        var quar = Math.floor(number / 1000000000000000); /* quadrillion */
        number -= quar * 1000000000000000;
        var trin = Math.floor(number / 1000000000000); /* trillion */
        number -= trin * 1000000000000;
        var Gn = Math.floor(number / 1000000000); /* billion */
        number -= Gn * 1000000000;
        var million = Math.floor(number / 1000000); /* million */
        number -= million * 1000000;
        var Hn = Math.floor(number / 1000); /* thousand */
        number -= Hn * 1000;
        var Dn = Math.floor(number / 100); /* Tens (deca) */
        number = number % 100; /* Ones */
        var tn = Math.floor(number / 10);
        var one = Math.floor(number % 10);
        var res = "";
    
        if (quintillion > 0) {
            res += (convert_number(quintillion) + " quintillion");
        }
        if (quar > 0) {
            res += (convert_number(quar) + " quadrillion");
        }
        if (trin > 0) {
            res += (convert_number(trin) + " trillion");
        }
        if (Gn > 0) {
            res += (convert_number(Gn) + " billion");
        }
        if (million > 0) {
            res += (((res == "") ? "" : " ") + convert_number(million) + " million");
        }
        if (Hn > 0) {
            res += (((res == "") ? "" : " ") + convert_number(Hn) + " Thousand");
        }
    
        if (Dn) {
            res += (((res == "") ? "" : " ") + convert_number(Dn) + " hundred");
        }
    
    
        var ones = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen", "Nineteen");
        var tens = Array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eigthy", "Ninety");
    
        if (tn > 0 || one > 0) {
            if (!(res == "")) {
                res += " and ";
            }
            if (tn < 2) {
                res += ones[tn * 10 + one];
            } else {
    
                res += tens[tn];
                if (one > 0) {
                    res += ("-" + ones[one]);
                }
            }
        }
    
        if (res == "") {
            console.log("Empty = " + number);
            res = "";
        }
        return res;
    }
    function is_numeric(mixed_var) {
        return (typeof mixed_var === 'number' || typeof mixed_var === 'string') && mixed_var !== '' && !isNaN(mixed_var);
    }
    
    0 讨论(0)
  • 2020-11-22 14:45

    A version with a compact object - for numbers from zero to 999.

    function wordify(n) {
        var word = [],
            numbers = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', t3: 'Thir', t5: 'Fif', t8: 'Eigh', 20: 'Twenty' },
            hundreds = 0 | (n % 1000) / 100,
            tens = 0 | (n % 100) / 10,
            ones = n % 10,
            part;
    
        if (n === 0) return 'Zero';
        if (hundreds) word.push(numbers[hundreds] + ' Hundred');
    
        if (tens === 0) {
            word.push(numbers[ones]);
        } else if (tens === 1) {
            word.push(numbers['1' + ones] || (numbers['t' + ones] || numbers[ones]) + 'teen');
        } else {
            part = numbers[tens + '0'] || (numbers['t' + tens] || numbers[tens]) + 'ty';
            word.push(numbers[ones] ? part + '-' + numbers[ones] : part);
        }
        return word.join(' ');
    }
    
    var i,
        output = document.getElementById('out');
    
    for (i = 0; i < 1e3; i++) output.innerHTML += wordify(i) + '\n';
    <pre id="out"></pre>

    0 讨论(0)
  • 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 );
    
    0 讨论(0)
  • 2020-11-22 14:47

    There are JS library for en_US and cs_CZ.
    You can use it standalone or as Node module.

    • Numbers2Words
    0 讨论(0)
  • 2020-11-22 14:47

    this is the solution for french language it's a fork for @gandil response

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <script type="text/javascript">
    var th = ['', ' mille', ' millions', ' milliards', ' billions', ' mille-billions', ' trillion'];
    var dg = ['zéro', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf'];
    var tn = ['dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf'];
    var tw = ['vingt', 'trente', 'quarante', 'cinquante', 'soixante', 'soixante-dix', 'quatre-vingts', 'quatre-vingt-dix'];
    
    function update(){
        var numString =   document.getElementById('number').value;
        if (numString == '0') {
            document.getElementById('container').innerHTML = 'Zéro';
            return;
        }
        if (numString == 0) {
            document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
            return;
        }
    
        var output = toWords(numString);
        //output.split('un mille').join('msille ');
        //output.replace('un cent', 'cent ');
        //print the output
        //if(output.length == 4){output = 'sss';}
        document.getElementById('container').innerHTML = output;
    }
    
    function toWords(s) {
    
        s = s.toString();
        s = s.replace(/[\, ]/g, '');
        if (s != parseFloat(s)) return 'not a number';
        var x = s.indexOf('.');
        if (x == -1) x = s.length;
        if (x > 15) return 'too big';
        var n = s.split('');
        var str = '';
        var sk = 0;
        for (var i = 0; i < x; i++) {
            if ((x - i) % 3 == 2) {
                if (n[i] == '1') {
                    str += tn[Number(n[i + 1])] + ' ';
                    i++;
                    sk = 1;
                } else if (n[i] != 0) {
                    str += tw[n[i] - 2] + ' ';
                    sk = 1;
                }
            } else if (n[i] != 0) {
                str += dg[n[i]] + ' ';
                //if((dg[n[i]] == 'un') && ((x - i) / 3 == 1)){str = 'cent ';}
                if ((x - i) % 3 == 0) {str += 'cent ';}
                sk = 1;
            }
            if ((x - i) % 3 == 1) {
                //test
                if((x - i - 1) / 3 == 1){
                    var long = str.length;
                    subs = str.substr(long-3);
                    if(subs.search("un")!= -1){
                        //str += 'OK';
                        str = str.substr(0, long-4);
                    }
    
                }
    
    
    
    
                //test
                if (sk) str += th[(x - i - 1) / 3] + ' ';
                sk = 0;
    
    
            }
        }
        if (x != s.length) {
            var y = s.length;
            str += 'point ';
            for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' ';
        }
        //if(str.length == 4){}
        str.replace(/\s+/g, ' ');
        return str.split('un cent').join('cent ');
        //return str.replace('un cent', 'cent ');
    }
    </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>
    

    i hope it will help

    0 讨论(0)
提交回复
热议问题