JavaScript numbers to Words

2019-01-01 01:06发布

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>

21条回答
姐姐魅力值爆表
2楼-- · 2019-01-01 01:35

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 );
查看更多
呛了眼睛熬了心
3楼-- · 2019-01-01 01:37

I know this problem had solved 3 years ago. I am posting this SPECIALLY FOR INDIAN DEVELOPERS

After spending some time in googling and playing with others code i made a quick fix and reusable function works well for numbers upto 99,99,99,999. use : number2text(1234.56); will return ONE THOUSAND TWO HUNDRED AND THIRTY-FOUR RUPEE AND FIFTY-SIX PAISE ONLY . enjoy !

function number2text(value) {
    var fraction = Math.round(frac(value)*100);
    var f_text  = "";

    if(fraction > 0) {
        f_text = "AND "+convert_number(fraction)+" PAISE";
    }

    return convert_number(value)+" RUPEE "+f_text+" ONLY";
}

function frac(f) {
    return f % 1;
}

function convert_number(number)
{
    if ((number < 0) || (number > 999999999)) 
    { 
        return "NUMBER OUT OF RANGE!";
    }
    var Gn = Math.floor(number / 10000000);  /* Crore */ 
    number -= Gn * 10000000; 
    var kn = Math.floor(number / 100000);     /* lakhs */ 
    number -= kn * 100000; 
    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 (Gn>0) 
    { 
        res += (convert_number(Gn) + " CRORE"); 
    } 
    if (kn>0) 
    { 
            res += (((res=="") ? "" : " ") + 
            convert_number(kn) + " LAKH"); 
    } 
    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", "EIGHTEEN","NINETEEN"); 
var tens = Array("", "", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY","SEVENTY", "EIGHTY", "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=="")
    { 
        res = "zero"; 
    } 
    return res;
}
查看更多
其实,你不懂
4楼-- · 2019-01-01 01:38

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

查看更多
心情的温度
5楼-- · 2019-01-01 01:42
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript">
var th = ['', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion'];
var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

function update(){
    var numString =   document.getElementById('number').value;
    if (numString == '0') {
        document.getElementById('container').innerHTML = 'Zero';
        return;
    }
    if (numString == 0) {
        document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
        return;
    }

    var output = toWords(numString);
    //print the output
    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 ((x - i) % 3 == 0) str += 'hundred ';
            sk = 1;
        }
        if ((x - i) % 3 == 1) {
            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]] + ' ';
    }
    return str.replace(/\s+/g, ' ');
}
</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>
查看更多
浮光初槿花落
6楼-- · 2019-01-01 01:43

I think, I have solution that's simpler and easier to understand; it goes by slicing the number, it works up to 99 lakhs crore.

function convert_to_word(num, ignore_ten_plus_check) {

var ones = [];
var tens = [];
var ten_plus = [];
ones["1"] = "one";
ones["2"] = "two";
ones["3"] = "three";
ones["4"] = "four";
ones["5"] = "five";
ones["6"] = "six";
ones["7"] = "seven";
ones["8"] = "eight";
ones["9"] = "nine";

ten_plus["10"] = "ten";
ten_plus["11"] = "eleven";
ten_plus["12"] = "twelve";
ten_plus["13"] = "thirteen";
ten_plus["14"] = "fourteen";
ten_plus["15"] = "fifteen";
ten_plus["16"] = "sixteen";
ten_plus["17"] = "seventeen";
ten_plus["18"] = "eighteen";
ten_plus["19"] = "nineteen";

tens["1"] = "ten";
tens["2"] = "twenty";
tens["3"] = "thirty";
tens["4"] = "fourty";
tens["5"] = "fifty";
tens["6"] = "sixty";
tens["7"] = "seventy";
tens["8"] = "eighty";
tens["9"] = "ninety";   

    var len = num.length;

    if(ignore_ten_plus_check != true && len >= 2) {
        var ten_pos = num.slice(len - 2, len - 1);
        if(ten_pos == "1") {
            return ten_plus[num.slice(len - 2, len)];
        } else if(ten_pos != 0) {
            return tens[num.slice(len - 2, len - 1)] + " " + ones[num.slice(len - 1, len)];
        }
    }

    return ones[num.slice(len - 1, len)];

}

function get_rupees_in_words(str, recursive_call_count) {
  if(recursive_call_count > 1) {
        return "conversion is not feasible";
    }
    var len = str.length;
    var words = convert_to_word(str, false);
    if(len == 2 || len == 1) {
    if(recursive_call_count == 0) {
        words = words +" rupees";
    }
        return words;
    }
    if(recursive_call_count == 0) {
        words = " and " + words +" rupees";
    }



var hundred = convert_to_word(str.slice(0, len-2), true);
  words = hundred != undefined ? hundred + " hundred " + words : words;
    if(len == 3) {
        return words;
    }

var thousand = convert_to_word(str.slice(0, len-3), false);
words = thousand != undefined ? thousand  + " thousand " + words : words;
if(len <= 5) {
    return words;
}

var lakh = convert_to_word(str.slice(0, len-5), false);
words =  lakh != undefined ? lakh + " lakh " + words : words;
if(len <= 7) {
    return words;
}

recursive_call_count = recursive_call_count + 1;
return get_rupees_in_words(str.slice(0, len-7), recursive_call_count) + " crore " + words;
}

Please check out my code pen

查看更多
无色无味的生活
7楼-- · 2019-01-01 01:43

I think this will help you

    aTens = [ "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy","Eighty", "Ninety"];

    aOnes = [ "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" ];
    var aUnits = "Thousand";
    function convertnumbertostring(){
       var num=prompt('','enter the number');
       var j=6;
       if(num.length<j){
       var y = ConvertToWords(num);
       alert(y);
       }else{
          alert('Enter the number of 5 letters')
       }
    };
    function ConvertToHundreds(num)
    {
       var cNum, nNum;
       var cWords = "";
       if (num > 99) {
          /* Hundreds. */
          cNum = String(num);
          nNum = Number(cNum.charAt(0));
          cWords += aOnes[nNum] + " Hundred";
          num %= 100;
          if (num > 0){
             cWords += " and "
          }
       }

       if (num > 19) {
          /* Tens. */
          cNum = String(num);
          nNum = Number(cNum.charAt(0));
          cWords += aTens[nNum - 2];
          num %= 10;
          if (num > 0){
             cWords += "-";
          }
       }
       if (num > 0) {
          /* Ones and teens. */
          nNum = Math.floor(num);
          cWords += aOnes[nNum];
       }
       return(cWords);

    }
    function ConvertToWords(num)
    {
       var cWords;
       for (var i = 0; num > 0; i++) { 
           if (num % 1000 > 0) {
              if (i != 0){
                 cWords = ConvertToHundreds(num) + " " + aUnits + " " + cWords;
              }else{
                 cWords = ConvertToHundreds(num) + " ";
              }        
           }
           num = (num / 1000);
       }
         return(cWords);
    }
查看更多
登录 后发表回答