JavaScript numbers to Words

匿名 (未验证) 提交于 2019-12-03 02:00:02

问题:

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?

  
Here The Numbers Printed

回答1:

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 

to

for (j = 0; j 

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]; // 


回答2:

Your problem is already solved but I am posting another way of doing it just for reference.

The code was written to be tested on node.js, but the functions should work fine when called within the browser. Also, this only handles the range [0,1000000], but can be easily adapted for bigger ranges.

#! /usr/bin/env node  var sys=require('sys');  // actual  conversion code starts here  var ones=['','one','two','three','four','five','six','seven','eight','nine']; var tens=['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']; var teens=['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];   function convert_millions(num){     if (num>=1000000){         return convert_millions(Math.floor(num/1000000))+" million "+convert_thousands(num%1000000);     }     else {         return convert_thousands(num);     } }  function convert_thousands(num){     if (num>=1000){         return convert_hundreds(Math.floor(num/1000))+" thousand "+convert_hundreds(num%1000);     }     else{         return convert_hundreds(num);     } }  function convert_hundreds(num){     if (num>99){         return ones[Math.floor(num/100)]+" hundred "+convert_tens(num%100);     }     else{         return convert_tens(num);     } }  function convert_tens(num){     if (num=10 && num


回答3:

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  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 0)              {                  res += ("-" + ones[one]);              }          }      }      if (res=="")     {          res = "zero";      }      return res; }


回答4:

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



回答5:

Here, I wrote an alternative solution:

1) The object containing the string constants:

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', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'],     sep: ['', ' thousand ', ' million ', ' billion ', ' trillion ', ' quadrillion ', ' quintillion ', ' sextillion '] };

2) The actual code:

(function( ones, tens, sep ) {      var input = document.getElementById( 'input' ),         output = document.getElementById( 'output' );      input.onkeyup = function() {         var val = this.value,             arr = [],             str = '',             i = 0;          if ( val.length === 0 ) {             output.textContent = 'Please type a number into the text-box.';             return;           }          val = parseInt( val, 10 );         if ( isNaN( val ) ) {             output.textContent = 'Invalid input.';             return;            }          while ( val ) {             arr.push( val % 1000 );             val = parseInt( val / 1000, 10 );            }          while ( arr.length ) {             str = (function( a ) {                 var x = Math.floor( a / 100 ),                     y = Math.floor( a / 10 ) % 10,                     z = a % 10;                  return ( x > 0 ? ones[x] + ' hundred ' : '' ) +                        ( y >= 2 ? tens[y] + ' ' + ones[z] : ones[10*y + z] );             })( arr.shift() ) + sep[i++] + str;         }          output.textContent = str;     };  })( NUMBER2TEXT.ones, NUMBER2TEXT.tens, NUMBER2TEXT.sep );

Live demo: http://jsfiddle.net/j5kdG/



回答6:

  
Here The Numbers Printed


回答7:

Try this,convert number to words

function convert(number) {      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",
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!