JavaScript数字到单词
我试图将数字转换成英文单词,例如1234会变成:“ 一千二百三十四 ”。
我的战术是这样的:
-
将数字分为三个,并将它们从右到左放在Array(
finlOutPut
)上。 -
将三个数字的每个组(
finlOutPut
数组中的每个单元格)转换为一个单词(这是triConvert
函数的作用)。 如果所有三位数都是零,则将它们转换为"dontAddBigSuffix"
-
从右到左,加上千,百万,等等 。 如果
finlOutPut
单元格等于"dontAddBigSufix"
(因为它只有零),不要添加单词并将单元格设置为" "
(无)。
这似乎工作得很好,但我遇到了一些问题,如19000000 9 ,转换为:“ 一千九百万 ”。 不知何故,当有几个零时,它会“忘记”最后的数字。
我做错了什么? 错误在哪里? 为什么它不完美?
<HTML> <HEAD> <meta http-equiv =“Content-Type”content =“text / html; charset = utf-8”/> <script type =“text / javascript”> 函数update(){ var bigNumArry = new Array('','千','million','billion','兆','quadrillion','quintillion'); var output =''; var numString = document.getElementById('number')。value; var finlOutPut = new Array(); if(numString =='0'){ document.getElementById('container')。innerHTML ='Zero'; 返回; } if(numString == 0){ document.getElementById('container')。innerHTML ='messeg告诉input数字'; 返回; } var i = numString.length; 我=我 - 1; //把这个数字切成三位数字并加到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); 一世 - ; numString = numString.substring(0,numString.length - 3); } finlOutPut.push(numString); finlOutPut.reverse(); //将每个三位数字转换成英文单词 //如果所有的数字都是零的triConvert //函数返回string“dontAddBigSufix” for(j = 0; j <finlOutPut.length; j ++){ finlOutPut [j] = triConvert(parseInt(finlOutPut [j])); } var bigScalCntr = 0; //这个int标志着亿万亿美元... Arry for(b = finlOutPut.length - 1; b> = 0; b--){ if(finlOutPut [b]!=“dontAddBigSufix”){ finlOutPut [b] = finlOutPut [b] + bigNumArry [bigScalCntr] +','; bigScalCntr ++; } else { //将finlOP [b]中的string从“dontAddBigSufix”replace为空string。 finlOutPut [b] =''; bigScalCntr ++; //提前柜台 } } //将输出Arry转换为更可打印的string for(n = 0; n <finlOutPut.length; n ++){ 输出+ = finlOutPut [n]; } document.getElementById('container')。innerHTML = output; //打印输出 } //简单的函数将数字转换为从1到999的单词 函数triConvert(num){ var ones = new Array('','one','two','three','4','5','6','7','8','9','10','十一“,”十二“,”十三“,”十四“,”十五“,”十六“,”十七“,”十八“,”十九“ var tens = new Array('','','二十','三十','四十','五十','六十','七十','八十','九十'); var hundred ='100'; var output =''; var numString = num.toString(); if(num == 0){ 返回'dontAddBigSufix'; } // 10,11,12,13 ... 19的情况 if(num <20){ 输出= ones [num]; 返回输出; } // 100以上 if(numString.length == 3){ output = ones [parseInt(numString.charAt(0))] + hundred; 输出+ =十[parseInt(numString.charAt(1))]; 输出+ = ones [parseInt(numString.charAt(2))]; 返回输出; } 输出+ =十[parseInt(numString.charAt(0))]; 输出+ = ones [parseInt(numString.charAt(1))]; 返回输出; } </ SCRIPT> </ HEAD> <BODY> <input type =“text” ID = “数量” 大小= “70” 的onkeyup = “更新();” / *此代码防止非数字字母* / 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”>这里打印的数字</ div> </ BODY> </ HTML>
当存在前导零数字时,JavaScript将parsing3个数字的组作为八进制数字。 当三位数字组全部为零时,无论基数是八进制还是十进制,结果都是相同的。
但是,当你给JavaScript'009'(或'008'),这是一个无效的八进制数,所以你回零。
如果你已经完成了从190,000,001到190,000,010的整个数字集,你会看到跳过“…,008”和“…,009”的JavaScript,但是发出“…,010”的“八”。 那就是'尤里卡'! 时刻。
更改:
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)); }
代码还在每个非零组之后加逗号,所以我玩了,find了正确的地方加逗号。
旧:
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]; }
新:
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]; }
你的问题已经解决了,但是我发布了另外一个方法来做参考。
代码被编写为在node.js上testing,但是在浏览器中调用时,函数应该可以正常工作。 此外,这只能处理范围[0,1000000],但可以很容易地适应更大的范围。
#! /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) return ones[num]; else if (num>=10 && num<20) return teens[num-10]; else{ return tens[Math.floor(num/10)]+" "+ones[num%10]; } } function convert(num){ if (num==0) return "zero"; else return convert_millions(num); } //end of conversion code //testing code begins here function main(){ var cases=[0,1,2,7,10,11,12,13,15,19,20,21,25,29,30,35,50,55,69,70,99,100,101,119,510,900,1000,5001,5019,5555,10000,11000,100000,199001,1000000,1111111,190000009]; for (var i=0;i<cases.length;i++ ){ sys.puts(cases[i]+": "+convert(cases[i])); } } main();
我知道这个问题已经在三年前解决了。 我发布这个特殊的印度开发商
花了一些时间在Google和其他人玩代码我做了一个快速修复和可重用的function适用于高达99,99,99,999的数字。 使用: number2text(1234.56);
将返回ONE THOUSAND TWO HUNDRED AND THIRTY-FOUR RUPEE AND FIFTY-SIX PAISE ONLY
。 请享用 !
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; }
有用于en_US和cs_CZ的 JS库。
您可以单独使用或作为Node模块使用。
- Numbers2Words
在这里,我写了一个替代解决scheme:
1)包含string常量的对象:
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)实际代码:
(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 );
现场演示: http : //jsfiddle.net/j5kdG/
<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>
试试这个,把数字转换成单词
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); }
这是一个解决scheme,将处理任何适合在string中的整数值。 我已经定义了“decillion”的数字,所以这个解决scheme应该精确到999 decillion。 之后你会得到像“十万亿”之类的东西。
JavaScript数字在“999999999999999”附近开始失败,所以convert函数只能使用string。
例子:
convert("365"); //=> "three hundred sixty-five" convert("10000000000000000000000000000230001010109"); //=> "ten thousand decillion two hundred thirty billion one million ten thousand one hundred nine"
码:
var lt20 = ["", "one", "two", "three", "four", "five", "six", "seven","eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ], tens = ["", "ten", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eightty", "ninety" ], scales = ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion" ], max = scales.length * 3; function convert(val) { var len; // special cases if (val[0] === "-") { return "negative " + convert(val.slice(1)); } if (val === "0") { return "zero"; } val = trim_zeros(val); len = val.length; // general cases if (len < max) { return convert_lt_max(val); } if (len >= max) { return convert_max(val); } } function convert_max(val) { return split_rl(val, max) .map(function (val, i, arr) { if (i < arr.length - 1) { return convert_lt_max(val) + " " + scales.slice(-1); } return convert_lt_max(val); }) .join(" "); } function convert_lt_max(val) { var l = val.length; if (l < 4) { return convert_lt1000(val).trim(); } else { return split_rl(val, 3) .map(convert_lt1000) .reverse() .map(with_scale) .reverse() .join(" ") .trim(); } } function convert_lt1000(val) { var rem, l; val = trim_zeros(val); l = val.length; if (l === 0) { return ""; } if (l < 3) { return convert_lt100(val); } if (l === 3) { //less than 1000 rem = val.slice(1); if (rem) { return lt20[val[0]] + " hundred " + convert_lt1000(rem); } else { return lt20[val[0]] + " hundred"; } } } function convert_lt100(val) { if (is_lt20(val)) { // less than 20 return lt20[val]; } else if (val[1] === "0") { return tens[val[0]]; } else { return tens[val[0]] + "-" + lt20[val[1]]; } } function split_rl(str, n) { // takes a string 'str' and an integer 'n'. Splits 'str' into // groups of 'n' chars and returns the result as an array. Works // from right to left. if (str) { return Array.prototype.concat .apply(split_rl(str.slice(0, (-n)), n), [str.slice(-n)]); } else { return []; } } function with_scale(str, i) { var scale; if (str && i > (-1)) { scale = scales[i]; if (scale !== undefined) { return str.trim() + " " + scale; } else { return convert(str.trim()); } } else { return ""; } } function trim_zeros(val) { return val.replace(/^0*/, ""); } function is_lt20(val) { return parseInt(val, 10) < 20; }
function intToEnglish(number){ var NS = [ {value: 1000000000000000000000, str: "sextillion"}, {value: 1000000000000000000, str: "quintillion"}, {value: 1000000000000000, str: "quadrillion"}, {value: 1000000000000, str: "trillion"}, {value: 1000000000, str: "billion"}, {value: 1000000, str: "million"}, {value: 1000, str: "thousand"}, {value: 100, str: "hundred"}, {value: 90, str: "ninety"}, {value: 80, str: "eighty"}, {value: 70, str: "seventy"}, {value: 60, str: "sixty"}, {value: 50, str: "fifty"}, {value: 40, str: "forty"}, {value: 30, str: "thirty"}, {value: 20, str: "twenty"}, {value: 19, str: "nineteen"}, {value: 18, str: "eighteen"}, {value: 17, str: "seventeen"}, {value: 16, str: "sixteen"}, {value: 15, str: "fifteen"}, {value: 14, str: "fourteen"}, {value: 13, str: "thirteen"}, {value: 12, str: "twelve"}, {value: 11, str: "eleven"}, {value: 10, str: "ten"}, {value: 9, str: "nine"}, {value: 8, str: "eight"}, {value: 7, str: "seven"}, {value: 6, str: "six"}, {value: 5, str: "five"}, {value: 4, str: "four"}, {value: 3, str: "three"}, {value: 2, str: "two"}, {value: 1, str: "one"} ]; var result = ''; for (var n of NS) { if(number>=n.value){ if(number<=20){ result += n.str; number -= n.value; if(number>0) result += ' '; }else{ var t = Math.floor(number / n.value); var d = number % n.value; if(d>0){ return intToEnglish(t) + ' ' + n.str +' ' + intToEnglish(d); }else{ return intToEnglish(t) + ' ' + n.str; } } } } return result; }
我修改了ŠimeVidas的发帖 – http://jsfiddle.net/j5kdG/在适当的位置包含美元,美分,逗号和“and”。; 如果需要“零美分”,或者如果没有提到美分,则有一个可选的结尾。
这个function结构让我感到头疼,但是我学到了很多东西。 感谢Sime。
有人可能会find一个更好的方式来处理这个问题。
码:
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 );
我想指出的是,原始逻辑在x11-x19之间的值不成立,其中x> = 1。例如,118返回“一百八十”。 这是因为这些数字由triConvert()中的以下代码处理:
//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; }
在这里,代表十位的字符用于索引在索引[1]处具有空string的tens[]
数组,因此118有效。
处理数百个(如果有的话)可能会更好,然后通过相同的逻辑来运行数十个。 代替:
//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;
我会build议:
// 100 and more if ( numString.length == 3 ) { output = hundreds[ parseInt( numString.charAt(0) ) ] + hundred ; num = num % 100 ; numString = num.toString() ; } if ( num < 20 ) { output += ones[num] ; } else { // 20-99 output += tens[ parseInt( numString.charAt(0) ) ] ; output += '-' + ones[ parseInt( numString.charAt(1) ) ] ; } return output;
在我看来,build议的代码既短又清晰,但我可能有偏见;-)
资料来源: http : //javascript.about.com/library/bltoword.htm我发现的最小的脚本:
<script type="text/javascript" src="toword.js"> var words = toWords(12345); console.log(words); </script>
请享用!
我尝试了穆罕默德的解决scheme,但有一些问题,并希望使用小数,所以我做了一些改变,并转换为咖啡脚本和angular。 请记住,js和coffeescript不是我的强项,请小心使用。
$scope.convert = (number, upper=0) -> number = +number # console.log "inside convert and the number is: " + 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 isNaN(number) console.log("NOT A NUMBER") alert("Not a number = ") return '' else console.log "at line 88 number is: " + number quintillion = Math.floor(number / 1000000000000000000) ### quintillion ### number -= quintillion * 1000000000000000000 quar = Math.floor(number / 1000000000000000) # console.log "at line 94 number is: " + number ### quadrillion ### number -= quar * 1000000000000000 trin = Math.floor(number / 1000000000000) # console.log "at line 100 number is: " + number ### trillion ### number -= trin * 1000000000000 Gn = Math.floor(number / 1000000000) # console.log "at line 105 number is: " + number ### billion ### number -= Gn * 1000000000 million = Math.floor(number / 1000000) # console.log "at line 111 number is: " + number ### million ### number -= million * 1000000 Hn = Math.floor(number / 1000) # console.log "at line 117 number is: " + number ### thousand ### number -= Hn * 1000 Dn = Math.floor(number / 100) # console.log "at line 123 number is: " + number ### Tens (deca) ### number = number % 100 # console.log "at line 128 number is: " + number ### Ones ### tn = Math.floor(number / 10) one = Math.floor(number % 10) # tn = Math.floor(number / 1) change = Math.round((number % 1) * 100) res = '' # console.log "before ifs" if quintillion > 0 res += $scope.convert(quintillion) + ' Quintillion' if quar > 0 res += $scope.convert(quar) + ' Quadrillion' if trin > 0 res += $scope.convert(trin) + ' Trillion' if Gn > 0 res += $scope.convert(Gn) + ' Billion' if million > 0 res += (if res == '' then '' else ' ') + $scope.convert(million) + ' Million' if Hn > 0 res += (if res == '' then '' else ' ') + $scope.convert(Hn) + ' Thousand' if Dn res += (if res == '' then '' else ' ') + $scope.convert(Dn) + ' Hundred' # console.log "the result is: " + res ones = Array('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eightteen', 'Nineteen') tens = Array('', '', 'Twenty', 'Thirty', 'Fourty', 'Fifty', 'Sixty', 'Seventy', 'Eigthy', 'Ninety') # console.log "the result at 161 is: " + res if tn > 0 or one > 0 if !(res == '') # res += ' and ' res += ' ' # console.log "the result at 164 is: " + res if tn < 2 res += ones[tn * 10 + one] # console.log "the result at 168is: " + res else res += tens[tn] if one > 0 res += '-' + ones[one] # console.log "the result at 173 is: " + res if change > 0 if res == '' res = change + "/100" else res += ' and ' + change + "/100" if res == '' console.log 'Empty = ' + number res = '' if +upper == 1 res = res.toUpperCase() $scope.newCheck.amountInWords = res return res
$ scope.is_numeric =(mixed_var) – >#console.log“mixed var is:”+ mixed_var(typeof mixed_var =='number'or typeof mixed_var =='string')and mixed_var!=''and!isNaN(mixed_var )
这里是我的另一个版本与一些unit testing。
不要使用大于Number.MAX_SAFE_INTEGER
数字。
describe("English Numerals Converter", function () { assertNumeral(0, "zero"); assertNumeral(1, "one"); assertNumeral(2, "two"); assertNumeral(3, "three"); assertNumeral(4, "four"); assertNumeral(5, "five"); assertNumeral(6, "six"); assertNumeral(7, "seven"); assertNumeral(8, "eight"); assertNumeral(9, "nine"); assertNumeral(10, "ten"); assertNumeral(11, "eleven"); assertNumeral(12, "twelve"); assertNumeral(13, "thirteen"); assertNumeral(14, "fourteen"); assertNumeral(15, "fifteen"); assertNumeral(16, "sixteen"); assertNumeral(17, "seventeen"); assertNumeral(18, "eighteen"); assertNumeral(19, "nineteen"); assertNumeral(20, "twenty"); assertNumeral(21, "twenty-one"); assertNumeral(22, "twenty-two"); assertNumeral(23, "twenty-three"); assertNumeral(30, "thirty"); assertNumeral(37, "thirty-seven"); assertNumeral(40, "forty"); assertNumeral(50, "fifty"); assertNumeral(60, "sixty"); assertNumeral(70, "seventy"); assertNumeral(80, "eighty"); assertNumeral(90, "ninety"); assertNumeral(99, "ninety-nine"); assertNumeral(100, "one hundred"); assertNumeral(101, "one hundred and one"); assertNumeral(102, "one hundred and two"); assertNumeral(110, "one hundred and ten"); assertNumeral(120, "one hundred and twenty"); assertNumeral(121, "one hundred and twenty-one"); assertNumeral(199, "one hundred and ninety-nine"); assertNumeral(200, "two hundred"); assertNumeral(999, "nine hundred and ninety-nine"); assertNumeral(1000, "one thousand"); assertNumeral(1001, "one thousand and one"); assertNumeral(1011, "one thousand and eleven"); assertNumeral(1111, "one thousand and one hundred and eleven"); assertNumeral(9999, "nine thousand and nine hundred and ninety-nine"); assertNumeral(10000, "ten thousand"); assertNumeral(20000, "twenty thousand"); assertNumeral(21000, "twenty-one thousand"); assertNumeral(90000, "ninety thousand"); assertNumeral(90001, "ninety thousand and one"); assertNumeral(90100, "ninety thousand and one hundred"); assertNumeral(90901, "ninety thousand and nine hundred and one"); assertNumeral(90991, "ninety thousand and nine hundred and ninety-one"); assertNumeral(90999, "ninety thousand and nine hundred and ninety-nine"); assertNumeral(91000, "ninety-one thousand"); assertNumeral(99999, "ninety-nine thousand and nine hundred and ninety-nine"); assertNumeral(100000, "one hundred thousand"); assertNumeral(999000, "nine hundred and ninety-nine thousand"); assertNumeral(1000000, "one million"); assertNumeral(10000000, "ten million"); assertNumeral(100000000, "one hundred million"); assertNumeral(1000000000, "one billion"); assertNumeral(1000000000000, "one trillion"); assertNumeral(1000000000000000, "one quadrillion"); assertNumeral(1000000000000000000, "one quintillion"); assertNumeral(1000000000000000000000, "one sextillion"); assertNumeral(-1, "minus one"); assertNumeral(-999, "minus nine hundred and ninety-nine"); function assertNumeral(number, numeral) { it(number + " is " + numeral, function () { expect(convert(number)).toBe(numeral); }); } }); function convert(n) { let NUMERALS = [ {value: 1000000000000000000000, str: "sextillion"}, {value: 1000000000000000000, str: "quintillion"}, {value: 1000000000000000, str: "quadrillion"}, {value: 1000000000000, str: "trillion"}, {value: 1000000000, str: "billion"}, {value: 1000000, str: "million"}, {value: 1000, str: "thousand"}, {value: 100, str: "hundred"}, {value: 90, str: "ninety"}, {value: 80, str: "eighty"}, {value: 70, str: "seventy"}, {value: 60, str: "sixty"}, {value: 50, str: "fifty"}, {value: 40, str: "forty"}, {value: 30, str: "thirty"}, {value: 20, str: "twenty"}, {value: 19, str: "nineteen"}, {value: 18, str: "eighteen"}, {value: 17, str: "seventeen"}, {value: 16, str: "sixteen"}, {value: 15, str: "fifteen"}, {value: 14, str: "fourteen"}, {value: 13, str: "thirteen"}, {value: 12, str: "twelve"}, {value: 11, str: "eleven"}, {value: 10, str: "ten"}, {value: 9, str: "nine"}, {value: 8, str: "eight"}, {value: 7, str: "seven"}, {value: 6, str: "six"}, {value: 5, str: "five"}, {value: 4, str: "four"}, {value: 3, str: "three"}, {value: 2, str: "two"}, {value: 1, str: "one"} ]; if (n < 0) { return "minus " + convert(-n); } else if (n === 0) { return "zero"; } else { let result = ""; for (let numeral of NUMERALS) { if (n >= numeral.value) { if (n < 100) { result += numeral.str; n -= numeral.value; if (n > 0) result += "-"; } else { let times = Math.floor(n / numeral.value); result += convert(times) + " " + numeral.str; n -= numeral.value * times; if (n > 0) result += " and "; } } } return result; } }
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
<script src="js/demo/numtoword.js" type="text/javascript"></script> HTML - Convert numbers to words using JavaScript</h1> <input id="Text1" type="text" onkeypress="return onlyNumbers(this.value);" onkeyup="NumToWord(this.value,'divDisplayWords');" maxlength="9" style="background-color: #efefef; border: 2px solid #CCCCC; font-size: large" /> <br /> <br /> <div id="divDisplayWords" style="font-size: 13; color: Teal; font-family: Arial;"> </div>
Indian Version
Updated version of @jasonhao 's answer for Indian currency
function intToEnglish(number){ var NS = [ {value: 10000000, str: "Cror"}, {value: 100000, str: "Lakhs"}, {value: 1000, str: "thousand"}, {value: 100, str: "hundred"}, {value: 90, str: "ninety"}, {value: 80, str: "eighty"}, {value: 70, str: "seventy"}, {value: 60, str: "sixty"}, {value: 50, str: "fifty"}, {value: 40, str: "forty"}, {value: 30, str: "thirty"}, {value: 20, str: "twenty"}, {value: 19, str: "nineteen"}, {value: 18, str: "eighteen"}, {value: 17, str: "seventeen"}, {value: 16, str: "sixteen"}, {value: 15, str: "fifteen"}, {value: 14, str: "fourteen"}, {value: 13, str: "thirteen"}, {value: 12, str: "twelve"}, {value: 11, str: "eleven"}, {value: 10, str: "ten"}, {value: 9, str: "nine"}, {value: 8, str: "eight"}, {value: 7, str: "seven"}, {value: 6, str: "six"}, {value: 5, str: "five"}, {value: 4, str: "four"}, {value: 3, str: "three"}, {value: 2, str: "two"}, {value: 1, str: "one"} ]; var result = ''; for (var n of NS) { if(number>=n.value){ if(number<=90){ result += n.str; number -= n.value; if(number>0) result += ' '; }else{ var t = Math.floor(number / n.value); console.log(t); var d = number % n.value; if(d>0){ return intToEnglish(t) + ' ' + n.str +' ' + intToEnglish(d); }else{ return intToEnglish(t) + ' ' + n.str; } } } } return result; }
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); }