J'essaie de convertir des nombres en mots anglais, par exemple 1234 deviendrait: " mille deux cent trente quatre ".
Ma tactique va comme ceci:
Séparez les chiffres en trois et placez-les sur Array (finlOutPut
), de droite à gauche.
Convertissez chaque groupe (chaque cellule du tableau finlOutPut
) de trois chiffres en un mot (en l’occurrence la fonction triConvert
). Si les trois chiffres sont zéro, convertissez-les en "dontAddBigSuffix"
De droite à gauche, ajoutez mille, millions, milliards, etc.. Si la cellule finlOutPut
est égale à "dontAddBigSufix"
(car il ne s'agissait que de zéros), n'ajoutez pas le mot et définissez la cellule sur " "
(rien).
Cela semble fonctionner assez bien, mais j'ai des problèmes avec des nombres comme 19000000 9 , convertis en: "cent quatre-vingt-dix millions". D'une certaine manière, il "oublie" les derniers chiffres lorsqu'il y a quelques zéros.Qu'ai-je fait de mal? Où est le bug? Pourquoi ça ne marche pas parfaitement?.
<html> <head> <meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" /> <type de script = "text/javascript"> function update () { var bigNumArry = new Array ('', 'mille', 'millions', 'milliards', 'trillions', 'quadrillions', 'quintillions'); var output = ''; var numString = document.getElementById ('nombre'). valeur; var finlOutPut = new Array (); if (numString == '0') { document.getElementById ('conteneur'). innerHTML = 'Zero'; revenir; } si (numString == 0) { document.getElementById ('conteneur'). innerHTML = 'message dit d'entrer des nombres'; revenir; } var i = numString.length; i = i - 1; // coupe le nombre en groupes de trois chiffres et les ajoute à 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); je--; numString = numString.substring (0, numString.length - 3); } finlOutPut.Push (numString); finlOutPut.reverse (); // convertit chaque groupe de trois chiffres en un mot anglais // si tous les chiffres sont à zéro, le triConvert // fonction renvoie la chaîne "dontAddBigSufix" pour (j = 0; j <finlOutPut.length; j ++) { finlOutPut [j] = triConvert (parseInt (finlOutPut [j])); } var bigScalCntr = 0; // cet int marque le milliard de milliards de milliards de dollars ... Arry pour (b = finlOutPut.length - 1; b> = 0; b -) { if (finlOutPut [b]! = "dontAddBigSufix") { finlOutPut [b] = finlOutPut [b] + bigNumArry [bigScalCntr] + ','; ' bigScalCntr ++; } autre { // remplace la chaîne sur finlOP [b] de "dontAddBigSufix" par String vide . finlOutPut [b] = ''; bigScalCntr ++; // avance le compteur } } // convertit la sortie en Arry, plus de chaîne imprimable pour (n = 0; n <finlOutPut.length; n ++) { sortie + = finlOutPut [n]; } document.getElementById ('conteneur'). innerHTML = résultat; // affiche le résultat } // fonction simple permettant de convertir des nombres en mots de 1 à 999 fonction triConvert (num) { var one = new Array ('', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', ' onze "," douze "," treize "," quatorze "," quinze "," seize "," dix-sept "," dix-huit "," dix-neuf "); var tens = new Array ('', '', 'vingt', 'trente', 'quarante', 'cinquante', 'soixante', 'soixante dix', 'soixante', quatre vingt, quatre-vingt-dix); var cent = 'cent'; var output = ''; var numString = num.toString (); si (num == 0) { retourne 'dontAddBigSufix'; } // le cas de 10, 11, 12, 13, .... 19 si (num <20) { sortie = ceux [num]; retourne la sortie; } // 100 et plus if (numString.length == 3) { output = ones [parseInt (numString.charAt (0))] + cent; sortie + = dizaines [parseInt (numString.charAt (1))]; sortie + = ones [parseInt (numString.charAt (2))]; retourne la sortie; } sortie + = dizaines [parseInt (numString.charAt (0))]; sortie + = ones [parseInt (numString.charAt (1))]; retourne le résultat; } </ script> </ head> <body> <input type = "text" id = "numéro" taille = "70" onkeyup = "update ();" /* ce code empêche les lettres non numériques */ onkeydown = "return (event.ctrlKey || event.altKey || (47 <event.keyCode && event.keyCode <58 && event.shiftKey == false) .__ | || event.keyCode <106) || (event.keyCode == 8) || (event.keyCode == 9) || (event.keyCode> 34 && event.keyCode <40) || (event.keyCode == 46)) "/> <br/> <div id = "container"> Ici les chiffres imprimés </ div> </ body> </ html>
<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 analyse le groupe de 3 nombres sous la forme d'un nombre octal lorsqu'il existe un zéro non significatif. Lorsque le groupe de trois chiffres est composé uniquement de zéros, le résultat est identique, que la base soit octale ou décimale.
Mais lorsque vous donnez à JavaScript '009' (ou '008'), il s'agit d'un nombre octal non valide. Vous obtenez donc zéro.
Si vous aviez parcouru l’ensemble des chiffres de 190 000 001 à 190 000 010, vous auriez vu JavaScript sauter '..., 008' et '..., 009' mais émettre 'huit' pour '..., 010'. C'est l'Eureka! moment.
Changement:
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));
}
Le code continuait également à ajouter des virgules après chaque groupe différent de zéro. J'ai donc joué avec et trouvé le bon endroit pour ajouter la virgule.
Vieux:
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];
}
Nouveau:
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];
}
Votre problème est déjà résolu, mais je poste une autre façon de le faire simplement pour référence.
Le code a été écrit pour être testé sur node.js, mais les fonctions devraient fonctionner correctement lorsqu'elles sont appelées dans le navigateur. De plus, cela ne gère que la plage [0,1000000], mais peut être facilement adapté pour des plages plus grandes.
#! /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();
Je sais que ce problème a été résolu il y a 3 ans. Je poste ceci SPÉCIALEMENT POUR LES DÉVELOPPEURS INDIENS
Après avoir passé du temps à googler et à jouer avec d’autres codes, j’ai créé une solution rapide et la fonction réutilisable fonctionne bien pour les nombres jusqu’à 99,99,99,999. use: number2text(1234.56);
retournera ONE THOUSAND TWO HUNDRED AND THIRTY-FOUR RUPEE AND FIFTY-SIX PAISE ONLY
. prendre plaisir !
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;
}
Il existe une bibliothèque JS pour en_US et cs_CZ.
Vous pouvez l’utiliser de manière autonome ou comme module de nœud.
<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>
Ici, j'ai écrit une solution alternative:
1) L'objet contenant les constantes de chaîne:
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) Le code actuel:
(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 );
Démo en direct:http://jsfiddle.net/j5kdG/
Essayez ceci, convertissez le nombre en mots
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);
}
Version indienne
Version mise à jour de la réponse de @jasonhao pour devise indienne
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;
}
Voici une solution qui gérera toute valeur entière qui correspond à une chaîne. J'ai défini des échelles de nombres allant jusqu'à "décillions". Cette solution devrait donc être précise jusqu'à 999 décillions. Après quoi vous obtenez des choses comme "mille décillions" et ainsi de suite.
Les nombres JavaScript commencent à échouer autour de "999999999999999" et la fonction de conversion ne fonctionne qu'avec des chaînes de nombres.
Exemples:
convert("365");
//=> "three hundred sixty-five"
convert("10000000000000000000000000000230001010109");
//=> "ten thousand decillion two hundred thirty billion one million ten thousand one hundred nine"
Code:
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;
}
J'ai modifié l'affichage de Šime Vidas - http://jsfiddle.net/j5kdG/ Pour inclure dollars, cents, virgules et "et" aux endroits appropriés. Il existe une fin facultative s’il faut "zéro cent" ou aucune mention de cent si 0.
Cette structure de fonction a fait ma tête un peu mais j'ai appris des tas. Merci Sime.
Quelqu'un pourrait trouver un meilleur moyen de traiter cela.
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 );
Source: http://javascript.about.com/library/bltoword.htm Plus petit script que j'ai trouvé:
<script type="text/javascript" src="toword.js">
var words = toWords(12345);
console.log(words);
</script>
Prendre plaisir!
Je pense que j'ai une solution plus simple et plus facile à comprendre; il va en coupant le nombre, il fonctionne jusqu'à 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;
}
Voici une autre version de moi avec quelques tests unitaires.
Ne l'utilisez pas avec des nombres plus grands que 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;
}
}
J'ai essayé la solution de Muhammad, mais j'avais quelques problèmes et je voulais utiliser des nombres décimaux. J'ai donc fait quelques changements et converti en coffeescript et angular. N'oubliez pas que js et coffeescript ne sont pas mes points forts, utilisez-les avec précaution.
$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 "la variable mélangée est:" + mixed_var (typeof mixed_var == 'nombre' ou typeof mixed_var == 'chaîne') et mixed_var! = '' et! isNaN (mixed_var)
Ceci est un simple numéro ES6 + fonction de mots. Vous pouvez simplement ajouter un tableau 'illions' pour étendre les chiffres. Version anglaise américaine . (non 'et' avant la fin)
// generic number to words
let digits = ['','one','two','three','four', 'five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
let ties = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
let illions = ['', 'thousand', 'million', 'billion', 'trillion'].reverse()
let join = (a, s) => a.filter(v => v).join(s || ' ')
let tens = s =>
digits[s] ||
join([ties[s[0]], digits[s[1]]], '-') // 21 -> twenty-one
let hundreds = s =>
join(
(s[0] !== '0' ? [digits[s[0]], 'hundred'] : [])
.concat( tens(s.substr(1,2)) ) )
let re = '^' + '(\\d{3})'.repeat(illions.length) + '$'
let numberToWords = n =>
// to filter non number or '', null, undefined, false, NaN
isNaN(Number(n)) || !n && n !== 0
? 'not a number'
: Number(n) === 0
? 'zero'
: Number(n) >= 10 ** (illions.length * 3)
? 'too big'
: String(n)
.padStart(illions.length * 3, '0')
.match(new RegExp(re))
.slice(1, illions.length + 1)
.reduce( (a, v, i) => v === '000' ? a : join([a, hundreds(v), illions[i]]), '')
// just for this question.
let update = () => {
let value = document.getElementById('number').value
document.getElementById('container').innerHTML = numberToWords(value)
}
Si quelqu'un veut le faire mais en espagnol (en espagnol), voici mon code basé sur celui de Hardik
function num2str(num, moneda) {
moneda = moneda || (num !== 1 ? "pesos" : "peso");
var fraction = Math.round(__cf_frac(num) * 100);
var f_text = " (" + pad(fraction, 2) + "/100 M.N.)";
return __cf_convert_number(num) + " " + moneda + f_text;
}
function __cf_frac(f) {
return f % 1;
}
function __cf_convert_number(number) {
if ((number < 0) || (number > 999999999)) {
throw Error("N\u00famero fuera de rango");
}
var millon = Math.floor(number / 1000000);
number -= millon * 1000000;
var cientosDeMiles = Math.floor(number / 100000);
number -= cientosDeMiles * 100000;
var miles = Math.floor(number / 1000);
number -= miles * 1000;
var centenas = Math.floor(number / 100);
number = number % 100;
var tn = Math.floor(number / 10);
var one = Math.floor(number % 10);
var res = "";
var cientos = Array("", "cien", "doscientos", "trescientos", "cuatrocientos", "quinientos", "seiscientos", "setecientos", "ochocientos", "novecientos");
if (millon > 0) {
res += (__cf_convert_number(millon) + (millon === 1 ? " mill\u00f3n" : " millones"));
}
if (cientosDeMiles > 0) {
res += (((res == "") ? "" : " ") +
cientos[cientosDeMiles] + (miles > 0 || centenas > 0 || tn > 0 || one < 0 ? (cientosDeMiles == 1 ? "to " : " ") : ""));
}
if (miles > 0) {
res += (((res == "") ? "" : " ") +
__cf_convert_number(miles) + " mil");
}
if (centenas) {
res += (((res == "") ? "" : " ") +
cientos[centenas] + (tn > 0 || one > 0 ? (centenas > 1 ? " " : "to ") : ""));
}
var ones = Array("", "un", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce", "quince", "dieciseis", "diecisiete", "dieciocho", "diecinueve");
var tens = Array("", "", "veinte", "treinta", "cuarenta", "cincuenta", "sesenta", "setenta", "ochenta", "noventa");
if (tn > 0 || one > 0) {
if (tn < 2) {
res += ones[tn * 10 + one];
}
else {
if (tn === 2 && one > 0)
res += "veinti" + ones[one];
else {
res += tens[tn];
if (one > 0) {
res += (" y " + ones[one]);
}
}
}
}
if (res == "") {
res = "cero";
}
return res.replace(" ", " ");
}
function pad(num, largo, char) {
char = char || '0';
num = num + '';
return num.length >= largo ? num : new Array(largo - num.length + 1).join(char) + num;
}
Résultat:
num2str(123456789)
"ciento veintitres millones cuatrocientos cincuenta y seis mil setecientos ochenta y nueve pesos (00/100 M.N.)"
<script src="http://www.ittutorials.in/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>
J'aimerais souligner que la logique d'origine échoue pour les valeurs comprises entre x11-x19, où x> = 1. Par exemple, 118 renvoie "cent huit". C'est parce que ces nombres sont traités par le code suivant dans 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;
}
ici, le caractère représentant le chiffre des dizaines est utilisé pour indexer le tableau tens[]
, qui a une chaîne vide à l'index [1], ainsi 118 devient 108.
Il serait peut-être préférable de traiter les centaines (le cas échéant) en premier, puis d'exécuter les unités et les dizaines dans la même logique. Au lieu de:
//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;
Je voudrais suggerer:
// 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;
Il me semble que le code suggéré est à la fois plus court et plus clair, mais je pourrais être biaisé ;-)
c'est la solution pour la langue française c'est une fourchette pour la réponse de @gandil
<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>
j'espère que cela aidera