Converta dígitos em palavras com JavaScript

Eu estou fazendo um código que converte a quantidade dada em palavras, heres é o que eu tenho depois de googling. Mas acho que é um pequeno código para conseguir uma tarefa simples. Duas expressões regulares e dois loops for , eu quero algo mais simples.

Eu estou tentando fazer o mais curto possível. e postarei o que eu aparecer

Alguma sugestão?

 var th = ['','thousand','million', 'billion','trillion']; 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 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 ((xi)%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) { // 0235 str += dg[n[i]] +' '; if ((xi)%3==0) str += 'hundred '; sk=1; } if ((xi)%3==1) { if (sk) str += th[(xi-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,' '); } 

Além disso, o código acima se converte em sistema de numeração inglês como Million / Billion, mas eu não quero o sistema de numeração do sul da Ásia. como em Lakhs e Crores

Aqui está um código mais curto. com um RegEx e sem loops. converte como você queria, no sistema de numeração do sul da Ásia

 var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen ']; var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety']; function inWords (num) { if ((num = num.toString()).length > 9) return 'overflow'; n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/); if (!n) return; var str = ''; str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : ''; str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : ''; str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : ''; str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : ''; str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : ''; return str; } 

A única limitação é que você pode converter no máximo 9 dígitos, o que eu acho que é mais que suficiente na maioria dos casos.

“Tarefa enganosamente simples”. – Potatoswatter

De fato. Há muitos diabinhos saindo nos detalhes desse problema. Foi muito divertido resolver isso.

EDIT: Esta atualização tem uma abordagem muito mais composicional. Anteriormente, havia uma grande function que envolvia algumas outras funções proprietárias. Em vez disso, desta vez definimos funções reutilizáveis ​​genéricas que podem ser usadas para muitas variedades de tarefas. Mais sobre isso depois de darmos uma olhada no numToWords

 // numToWords :: (Number a, String a) => a -> String let numToWords = n => { let a = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ]; let b = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ]; let g = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion' ]; // this part is really nasty still // it might edit this again later to show how Monoids could fix this up let makeGroup = ([ones,tens,huns]) => { return [ num(huns) === 0 ? '' : a[huns] + ' hundred ', num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '', a[tens+ones] || a[ones] ].join(''); }; // "thousands" constructor; no real good names for this, i guess let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`; // execute ! if (typeof n === 'number') return numToWords(String(n)); if (n === '0') return 'zero'; return comp (chunk(3)) (reverse) (arr(n)) .map(makeGroup) .map(thousand) .filter(comp(not)(isEmpty)) .reverse() .join(' '); }; 

Aqui estão as dependencies:

Você perceberá que isso não é necessário, pois suas intenções são imediatamente claras. chunk pode ser o único que leva um momento para digerir, mas realmente não é tão ruim. Além disso, o nome da function nos dá uma boa indicação do que ela faz, e provavelmente é uma function que encontramos antes.

 const arr = x => Array.from(x); const num = x => Number(x) || 0; const str = x => String(x); const isEmpty = xs => xs.length === 0; const take = n => xs => xs.slice(0,n); const drop = n => xs => xs.slice(n); const reverse = xs => xs.slice(0).reverse(); const comp = f => g => x => f (g (x)); const not = x => !x; const chunk = n => xs => isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))]; 

“Então, isso faz melhor?”

Veja como o código foi limpo significativamente

 // NEW CODE (truncated) return comp (chunk(3)) (reverse) (arr(n)) .map(makeGroup) .map(thousand) .filter(comp(not)(isEmpty)) .reverse() .join(' '); // OLD CODE (truncated) let grp = n => ('000' + n).substr(-3); let rem = n => n.substr(0, n.length - 3); let cons = xs => x => g => x ? [x, g && ' ' + g || '', ' ', xs].join('') : xs; let iter = str => i => x => r => { if (x === '000' && r.length === 0) return str; return iter(cons(str)(fmt(x))(g[i])) (i+1) (grp(r)) (rem(r)); }; return iter('')(0)(grp(String(n)))(rem(String(n))); 

Mais importante ainda, as funções de utilidade que adicionamos no novo código podem ser usadas em outros lugares do seu aplicativo. Isso significa que, como um efeito colateral da implementação do numToWords , obtemos as outras funções gratuitamente. Refrigerante bônus!

Alguns testes

 console.log(numToWords(11009)); //=> eleven thousand nine console.log(numToWords(10000001)); //=> ten million one console.log(numToWords(987)); //=> nine hundred eighty-seven console.log(numToWords(1015)); //=> one thousand fifteen console.log(numToWords(55111222333)); //=> fifty-five billion one hundred eleven million two hundred // twenty-two thousand three hundred thirty-three console.log(numToWords("999999999999999999999991")); //=> nine hundred ninety-nine sextillion nine hundred ninety-nine // quintillion nine hundred ninety-nine quadrillion nine hundred // ninety-nine trillion nine hundred ninety-nine billion nine // hundred ninety-nine million nine hundred ninety-nine thousand // nine hundred ninety-one console.log(numToWords(6000753512)); //=> six billion seven hundred fifty-three thousand five hundred // twelve 

Demo executável

 const arr = x => Array.from(x); const num = x => Number(x) || 0; const str = x => String(x); const isEmpty = xs => xs.length === 0; const take = n => xs => xs.slice(0,n); const drop = n => xs => xs.slice(n); const reverse = xs => xs.slice(0).reverse(); const comp = f => g => x => f (g (x)); const not = x => !x; const chunk = n => xs => isEmpty(xs) ? [] : [take(n)(xs), ...chunk (n) (drop (n) (xs))]; // numToWords :: (Number a, String a) => a -> String let numToWords = n => { let a = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ]; let b = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ]; let g = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion' ]; // this part is really nasty still // it might edit this again later to show how Monoids could fix this up let makeGroup = ([ones,tens,huns]) => { return [ num(huns) === 0 ? '' : a[huns] + ' hundred ', num(ones) === 0 ? b[tens] : b[tens] && b[tens] + '-' || '', a[tens+ones] || a[ones] ].join(''); }; let thousand = (group,i) => group === '' ? group : `${group} ${g[i]}`; if (typeof n === 'number') return numToWords(String(n)); else if (n === '0') return 'zero'; else return comp (chunk(3)) (reverse) (arr(n)) .map(makeGroup) .map(thousand) .filter(comp(not)(isEmpty)) .reverse() .join(' '); }; console.log(numToWords(11009)); //=> eleven thousand nine console.log(numToWords(10000001)); //=> ten million one console.log(numToWords(987)); //=> nine hundred eighty-seven console.log(numToWords(1015)); //=> one thousand fifteen console.log(numToWords(55111222333)); //=> fifty-five billion one hundred eleven million two hundred // twenty-two thousand three hundred thirty-three console.log(numToWords("999999999999999999999991")); //=> nine hundred ninety-nine sextillion nine hundred ninety-nine // quintillion nine hundred ninety-nine quadrillion nine hundred // ninety-nine trillion nine hundred ninety-nine billion nine // hundred ninety-nine million nine hundred ninety-nine thousand // nine hundred ninety-one console.log(numToWords(6000753512)); //=> six billion seven hundred fifty-three thousand five hundred // twelve 

Passei algum tempo desenvolvendo uma solução melhor para isso. Ele pode lidar com números muito grandes, mas depois de obter mais de 16 dígitos você passa o número como uma string. Algo sobre o limite de números JavaScript.

  function numberToEnglish( n ) { var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and'; /* Remove spaces and commas */ string = string.replace(/[, ]/g,""); /* Is number zero? */ if( parseInt( string ) === 0 ) { return 'zero'; } /* Array of units as words */ units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ]; /* Array of tens as words */ tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ]; /* Array of scales as words */ scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ]; /* Split user arguemnt into 3 digit chunks from right to left */ start = string.length; chunks = []; while( start > 0 ) { end = start; chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) ); } /* Check if function has enough scale words to be able to stringify the user argument */ chunksLen = chunks.length; if( chunksLen > scales.length ) { return ''; } /* Stringify each integer in each chunk */ words = []; for( i = 0; i < chunksLen; i++ ) { chunk = parseInt( chunks[i] ); if( chunk ) { /* Split chunk into array of individual integers */ ints = chunks[i].split( '' ).reverse().map( parseFloat ); /* If tens integer is 1, ie 10, then add 10 to units integer */ if( ints[1] === 1 ) { ints[0] += 10; } /* Add scale word if chunk is not zero and array item exists */ if( ( word = scales[i] ) ) { words.push( word ); } /* Add unit word if array item exists */ if( ( word = units[ ints[0] ] ) ) { words.push( word ); } /* Add tens word if array item exists */ if( ( word = tens[ ints[1] ] ) ) { words.push( word ); } /* Add 'and' string after units or tens integer if: */ if( ints[0] || ints[1] ) { /* Chunk has a hundreds integer or chunk is the first of multiple chunks */ if( ints[2] || ! i && chunksLen ) { words.push( and ); } } /* Add hundreds word if array item exists */ if( ( word = units[ ints[2] ] ) ) { words.push( word + ' hundred' ); } } } return words.reverse().join( ' ' ); } // - - - - - Tests - - - - - - function test(v) { var sep = ('string'==typeof v)?'"':''; console.log("numberToEnglish("+sep + v.toString() + sep+") = "+numberToEnglish(v)); } test(2); test(721); test(13463); test(1000001); test("21,683,200,000,621,384"); 

Você pode querer tentar recursivo. Ele funciona para números entre 0 e 999999. Lembre-se de que (~~) faz o mesmo que Math.floor

 var num = "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split(" "); var tens = "twenty thirty forty fifty sixty seventy eighty ninety".split(" "); function number2words(n){ if (n < 20) return num[n]; var digit = n%10; if (n < 100) return tens[~~(n/10)-2] + (digit? "-" + num[digit]: ""); if (n < 1000) return num[~~(n/100)] +" hundred" + (n%100 == 0? "": " " + number2words(n%100)); return number2words(~~(n/1000)) + " thousand" + (n%1000 != 0? " " + number2words(n%1000): ""); } 

insira a descrição da imagem aqui

    HTML - Convert numbers to words using JavaScript    

HTML - Convert numbers to words using JavaScript



A conversão da string de input em um número, em vez de mantê-la como uma string, limita a solução ao valor flutuante / inteiro máximo permitido nessa máquina / navegador. Meu script abaixo lida com moeda de até 1 trilhão de dólares – 1 cent :-). Eu posso ser estendido para lidar com até 999 trilhões, adicionando 3 ou 4 linhas de código.

 var ones = ["","One","Two","Three","Four","Five","Six","Seven","Eight", "Nine","Ten","Eleven","Twelve","Thirteen","Fourteen", "Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"]; var tens = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy", "Eighty","Ninety"]; function words999(n999) { // n999 is an integer less than or equal to 999. // // Accept any 3 digit int incl 000 & 999 and return words. // var words = ''; var Hn = 0; var n99 = 0; Hn = Math.floor(n999 / 100); // # of hundreds in it if (Hn > 0) { // if at least one 100 words = words99(Hn) + " Hundred"; // one call for hundreds } n99 = n999 - (Hn * 100); // subtract the hundreds. words += ((words == '')?'':' ') + words99(n99); // combine the hundreds with tens & ones. return words; } // function words999( n999 ) function words99(n99) { // n99 is an integer less than or equal to 99. // // Accept any 2 digit int incl 00 & 99 and return words. // var words = ''; var Dn = 0; var Un = 0; Dn = Math.floor(n99 / 10); // # of tens Un = n99 % 10; // units if (Dn > 0 || Un > 0) { if (Dn < 2) { words += ones[Dn * 10 + Un]; // words for a # < 20 } else { words += tens[Dn]; if (Un > 0) words += "-" + ones[Un]; } } // if ( Dn > 0 || Un > 0 ) return words; } // function words99( n99 ) function getAmtInWords(id1, id2) { // use numeric value of id1 to populate text in id2 // // Read numeric amount field and convert into word amount // var t1 = document.getElementById(id1).value; var t2 = t1.trim(); amtStr = t2.replace(/,/g,''); // $123,456,789.12 = 123456789.12 dotPos = amtStr.indexOf('.'); // position of dot before cents, -ve if it doesn't exist. if (dotPos > 0) { dollars = amtStr.slice(0,dotPos); // 1234.56 = 1234 cents = amtStr.slice(dotPos+1); // 1234.56 = .56 } else if (dotPos == 0) { dollars = '0'; cents = amtStr.slice(dotPos+1); // 1234.56 = .56 } else { dollars = amtStr.slice(0); // 1234 = 1234 cents = '0'; } t1 = '000000000000' + dollars; // to extend to trillion, use 15 zeros dollars = t1.slice(-12); // and -15 here. billions = Number(dollars.substr(0,3)); millions = Number(dollars.substr(3,3)); thousands = Number(dollars.substr(6,3)); hundreds = Number(dollars.substr(9,3)); t1 = words999(billions); bW = t1.trim(); // Billions in words t1 = words999(millions); mW = t1.trim(); // Millions in words t1 = words999(thousands); tW = t1.trim(); // Thousands in words t1 = words999(hundreds); hW = t1.trim(); // Hundreds in words t1 = words99(cents); cW = t1.trim(); // Cents in words var totAmt = ''; if (bW != '') totAmt += ((totAmt != '') ? ' ' : '') + bW + ' Billion'; if (mW != '') totAmt += ((totAmt != '') ? ' ' : '') + mW + ' Million'; if (tW != '') totAmt += ((totAmt != '') ? ' ' : '') + tW + ' Thousand'; if (hW != '') totAmt += ((totAmt != '') ? ' ' : '') + hW + ' Dollars'; if (cW != '') totAmt += ((totAmt != '') ? ' and ' : '') + cW + ' Cents'; // alert('totAmt = ' + totAmt); // display words in a alert t1 = document.getElementById(id2).value; t2 = t1.trim(); if (t2 == '') document.getElementById(id2).value = totAmt; return false; } // function getAmtInWords( id1, id2 ) // ======================== [ End Code ] ==================================== 

Isso é em resposta ao comentário de @ LordZardeck à excelente resposta de @ naomik acima . Desculpe, eu teria comentado diretamente, mas nunca postei antes, então não tenho o privilégio de fazer isso, então estou postando aqui.

De qualquer forma, eu acabei de traduzir a versão ES5 para uma forma mais legível no fim de semana passado, então estou compartilhando aqui. Isso deve ser fiel ao original (incluindo a edição recente) e espero que a nomeação seja clara e precisa.

 function int_to_words(int) { if (int === 0) return 'zero'; var ONES = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']; var TENS = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']; var SCALE = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion']; // Return string of first three digits, padded with zeros if needed function get_first(str) { return ('000' + str).substr(-3); } // Return string of digits with first three digits chopped off function get_rest(str) { return str.substr(0, str.length - 3); } // Return string of triplet convereted to words function triplet_to_words(_3rd, _2nd, _1st) { return (_3rd == '0' ? '' : ONES[_3rd] + ' hundred ') + (_1st == '0' ? TENS[_2nd] : TENS[_2nd] && TENS[_2nd] + '-' || '') + (ONES[_2nd + _1st] || ONES[_1st]); } // Add to words, triplet words with scale word function add_to_words(words, triplet_words, scale_word) { return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + words : words; } function iter(words, i, first, rest) { if (first == '000' && rest.length === 0) return words; return iter(add_to_words(words, triplet_to_words(first[0], first[1], first[2]), SCALE[i]), ++i, get_first(rest), get_rest(rest)); } return iter('', 0, get_first(String(int)), get_rest(String(int))); } 
 var inWords = function(totalRent){ //console.log(totalRent); var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen ']; var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety']; var number = parseFloat(totalRent).toFixed(2).split("."); var num = parseInt(number[0]); var digit = parseInt(number[1]); //console.log(num); if ((num.toString()).length > 9) return 'overflow'; var n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/); var d = ('00' + digit).substr(-2).match(/^(\d{2})$/);; if (!n) return; var str = ''; str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : ''; str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : ''; str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : ''; str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : ''; str += (n[5] != 0) ? (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'Rupee ' : ''; str += (d[1] != 0) ? ((str != '' ) ? "and " : '') + (a[Number(d[1])] || b[d[1][0]] + ' ' + a[d[1][1]]) + 'Paise ' : 'Only!'; console.log(str); return str; } 

Este é o código modificado suporta para Rúpia Indiana com 2 casas decimais.

Eu gosto do resultado que obtive aqui, que acho fácil de ler e curto o suficiente para me encheckboxr como uma solução.

 function NumInWords (number) { const first = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen ']; const tens = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety']; const mad = ['', 'thousand', 'million', 'billion', 'trillion']; let word = ''; for (let i = 0; i < mad.length; i++) { let tempNumber = number%(100*Math.pow(1000,i)); if (Math.floor(tempNumber/Math.pow(1000,i)) !== 0) { if (Math.floor(tempNumber/Math.pow(1000,i)) < 20) { word = first[Math.floor(tempNumber/Math.pow(1000,i))] + mad[i] + ' ' + word; } else { word = tens[Math.floor(tempNumber/(10*Math.pow(1000,i)))] + '-' + first[Math.floor(tempNumber/Math.pow(1000,i))%10] + mad[i] + ' ' + word; } } tempNumber = number%(Math.pow(1000,i+1)); if (Math.floor(tempNumber/(100*Math.pow(1000,i))) !== 0) word = first[Math.floor(tempNumber/(100*Math.pow(1000,i)))] + 'hunderd ' + word; } return word; } console.log(NumInWords(89754697976431)) 

Modifiquei o código do @McShaman, converti-o para o CoffeeScript e adicionei documentos via JSNice . Aqui está o resultado, para os interessados ​​(inglês):

 ### Convert an integer to an English string equivalent @param {Integer} number the integer to be converted @return {String} the English number equivalent ### inWords = (number) -> ### @property {Array} ### englishIntegers = [ "" "one " "two " "three " "four " "five " "six " "seven " "eight " "nine " "ten " "eleven " "twelve " "thirteen " "fourteen " "fifteen " "sixteen " "seventeen " "eighteen " "nineteen " ] ### @property {Array} ### englishIntegerTens = [ "" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety" ] ### @property {Array} ### englishIntegerThousands = [ "thousand" "million" "" ] number = number.toString() return "" if number.length > 9 ### @property {string} ### number = ("000000000" + number).substr(-9) ### @property {(Array.|null)} ### number = number.match(/.{3}/g) ### @property {string} ### convertedWords = "" ### @property {number} ### i = 0 while i < englishIntegerThousands.length ### @property {string} ### currentNumber = number[i] ### @property {string} ### tempResult = "" tempResult += (if convertedWords isnt "" then " " + englishIntegerThousands[i] + " " else "") tempResult += (if currentNumber[0] isnt 0 then englishIntegers[Number(currentNumber[0])] + "hundred " else "") ### @property {string} ### currentNumber = currentNumber.substr(1) tempResult += (if currentNumber isnt 0 then ((if tempResult isnt "" then "and " else "")) + (englishIntegers[Number(currentNumber)] or englishIntegerTens[currentNumber[0]] + " " + englishIntegers[currentNumber[1]]) else "") convertedWords += tempResult i++ convertedWords 

Embora, essa pergunta tenha sido respondida – ainda quero compartilhar algo que desenvolvi recentemente em java script (baseado na lógica de uma antiga implementação de C # .Net que encontrei na Internet) para converter valores de moeda indiana em Palavras. Pode lidar com até 40 dígitos. Você pode dar uma olhada.

Uso: InrToWordConverter.Initialize () ;. var inWords = InrToWordConverter.ConvertToWord (quantidade);

Implementação:

 htPunctuation = {}; listStaticSuffix = {}; listStaticPrefix = {}; listHelpNotation = {}; var InrToWordConverter = function () { }; InrToWordConverter.Initialize = function () { InrToWordConverter.LoadStaticPrefix(); InrToWordConverter.LoadStaticSuffix(); InrToWordConverter.LoadHelpofNotation(); }; InrToWordConverter.ConvertToWord = function (value) { value = value.toString(); if (value) { var tokens = value.split("."); var rsPart = ""; var psPart = ""; if (tokens.length === 2) { rsPart = String.trim(tokens[0]) || "0"; psPart = String.trim(tokens[1]) || "0"; } else if (tokens.length === 1) { rsPart = String.trim(tokens[0]) || "0"; psPart = "0"; } else { rsPart = "0"; psPart = "0"; } htPunctuation = {}; var rsInWords = InrToWordConverter.ConvertToWordInternal(rsPart) || "Zero"; var psInWords = InrToWordConverter.ConvertToWordInternal(psPart) || "Zero"; var result = "Rupees " + rsInWords + "and " + psInWords + " Paise."; return result; } }; InrToWordConverter.ConvertToWordInternal = function (value) { var convertedString = ""; if (!(value.toString().length > 40)) { if (InrToWordConverter.IsNumeric(value.toString())) { try { var strValue = InrToWordConverter.Reverse(value); switch (strValue.length) { case 1: if (parseInt(strValue.toString()) > 0) { convertedString = InrToWordConverter.GetWordConversion(value); } else { convertedString = "Zero "; } break; case 2: convertedString = InrToWordConverter.GetWordConversion(value); break; default: InrToWordConverter.InsertToPunctuationTable(strValue); InrToWordConverter.ReverseHashTable(); convertedString = InrToWordConverter.ReturnHashtableValue(); break; } } catch (exception) { convertedString = "Unexpected Error Occured 
"; } } else { convertedString = "Please Enter Numbers Only, Decimal Values Are not supported"; } } else { convertedString = "Please Enter Value in Less Then or Equal to 40 Digit"; } return convertedString; }; InrToWordConverter.IsNumeric = function (valueInNumeric) { var isFine = true; valueInNumeric = valueInNumeric || ""; var len = valueInNumeric.length; for (var i = 0; i < len; i++) { var ch = valueInNumeric[i]; if (!(ch >= '0' && ch < = '9')) { isFine = false; break; } } return isFine; }; InrToWordConverter.ReturnHashtableValue = function () { var strFinalString = ""; var keysArr = []; for (var key in htPunctuation) { keysArr.push(key); } for (var i = keysArr.length - 1; i >= 0; i--) { var hKey = keysArr[i]; if (InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) !== "") { strFinalString = strFinalString + InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) + InrToWordConverter.StaticPrefixFind((hKey).toString()); } } return strFinalString; }; InrToWordConverter.ReverseHashTable = function () { var htTemp = {}; for (var key in htPunctuation) { var item = htPunctuation[key]; htTemp[key] = InrToWordConverter.Reverse(item.toString()); } htPunctuation = {}; htPunctuation = htTemp; }; InrToWordConverter.InsertToPunctuationTable = function (strValue) { htPunctuation[1] = strValue.substr(0, 3).toString(); var j = 2; for (var i = 3; i < strValue.length; i = i + 2) { if (strValue.substr(i).length > 0) { if (strValue.substr(i).length >= 2) { htPunctuation[j] = strValue.substr(i, 2).toString(); } else { htPunctuation[j] = strValue.substr(i, 1).toString(); } } else { break; } j++; } }; InrToWordConverter.Reverse = function (strValue) { var reversed = ""; for (var i in strValue) { var ch = strValue[i]; reversed = ch + reversed; } return reversed; }; InrToWordConverter.GetWordConversion = function (inputNumber) { var toReturnWord = ""; if (inputNumber.length < = 3 && inputNumber.length > 0) { if (inputNumber.length === 3) { if (parseInt(inputNumber.substr(0, 1)) > 0) { toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1)) + "Hundred "; } var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 2)); if (tempString === "") { toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1) + "0"); toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(2, 1)); } toReturnWord = toReturnWord + tempString; } if (inputNumber.length === 2) { var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 2)); if (tempString === "") { toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1) + "0"); toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1)); } toReturnWord = toReturnWord + tempString; } if (inputNumber.length === 1) { toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1)); } } return toReturnWord; }; InrToWordConverter.StaticSuffixFind = function (numberKey) { var valueFromNumber = ""; for (var key in listStaticSuffix) { if (String.trim(key.toString()) === String.trim(numberKey)) { valueFromNumber = listStaticSuffix[key].toString(); break; } } return valueFromNumber; }; InrToWordConverter.StaticPrefixFind = function (numberKey) { var valueFromNumber = ""; for (var key in listStaticPrefix) { if (String.trim(key) === String.trim(numberKey)) { valueFromNumber = listStaticPrefix[key].toString(); break; } } return valueFromNumber; }; InrToWordConverter.StaticHelpNotationFind = function (numberKey) { var helpText = ""; for (var key in listHelpNotation) { if (String.trim(key.toString()) === String.trim(numberKey)) { helpText = listHelpNotation[key].toString(); break; } } return helpText; }; InrToWordConverter.LoadStaticPrefix = function () { listStaticPrefix[2] = "Thousand "; listStaticPrefix[3] = "Lac "; listStaticPrefix[4] = "Crore "; listStaticPrefix[5] = "Arab "; listStaticPrefix[6] = "Kharab "; listStaticPrefix[7] = "Neel "; listStaticPrefix[8] = "Padma "; listStaticPrefix[9] = "Shankh "; listStaticPrefix[10] = "Maha-shankh "; listStaticPrefix[11] = "Ank "; listStaticPrefix[12] = "Jald "; listStaticPrefix[13] = "Madh "; listStaticPrefix[14] = "Paraardha "; listStaticPrefix[15] = "Ant "; listStaticPrefix[16] = "Maha-ant "; listStaticPrefix[17] = "Shisht "; listStaticPrefix[18] = "Singhar "; listStaticPrefix[19] = "Maha-singhar "; listStaticPrefix[20] = "Adant-singhar "; }; InrToWordConverter.LoadStaticSuffix = function () { listStaticSuffix[1] = "One "; listStaticSuffix[2] = "Two "; listStaticSuffix[3] = "Three "; listStaticSuffix[4] = "Four "; listStaticSuffix[5] = "Five "; listStaticSuffix[6] = "Six "; listStaticSuffix[7] = "Seven "; listStaticSuffix[8] = "Eight "; listStaticSuffix[9] = "Nine "; listStaticSuffix[10] = "Ten "; listStaticSuffix[11] = "Eleven "; listStaticSuffix[12] = "Twelve "; listStaticSuffix[13] = "Thirteen "; listStaticSuffix[14] = "Fourteen "; listStaticSuffix[15] = "Fifteen "; listStaticSuffix[16] = "Sixteen "; listStaticSuffix[17] = "Seventeen "; listStaticSuffix[18] = "Eighteen "; listStaticSuffix[19] = "Nineteen "; listStaticSuffix[20] = "Twenty "; listStaticSuffix[30] = "Thirty "; listStaticSuffix[40] = "Fourty "; listStaticSuffix[50] = "Fifty "; listStaticSuffix[60] = "Sixty "; listStaticSuffix[70] = "Seventy "; listStaticSuffix[80] = "Eighty "; listStaticSuffix[90] = "Ninty "; }; InrToWordConverter.LoadHelpofNotation = function () { listHelpNotation[2] = "=1,000 (3 Trailing Zeros)"; listHelpNotation[3] = "=1,00,000 (5 Trailing Zeros)"; listHelpNotation[4] = "=1,00,00,000 (7 Trailing Zeros)"; listHelpNotation[5] = "=1,00,00,00,000 (9 Trailing Zeros)"; listHelpNotation[6] = "=1,00,00,00,00,000 (11 Trailing Zeros)"; listHelpNotation[7] = "=1,00,00,00,00,00,000 (13 Trailing Zeros)"; listHelpNotation[8] = "=1,00,00,00,00,00,00,000 (15 Trailing Zeros)"; listHelpNotation[9] = "=1,00,00,00,00,00,00,00,000 (17 Trailing Zeros)"; listHelpNotation[10] = "=1,00,00,00,00,00,00,00,00,000 (19 Trailing Zeros)"; listHelpNotation[11] = "=1,00,00,00,00,00,00,00,00,00,000 (21 Trailing Zeros)"; listHelpNotation[12] = "=1,00,00,00,00,00,00,00,00,00,00,000 (23 Trailing Zeros)"; listHelpNotation[13] = "=1,00,00,00,00,00,00,00,00,00,00,00,000 (25 Trailing Zeros)"; listHelpNotation[14] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,000 (27 Trailing Zeros)"; listHelpNotation[15] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (29 Trailing Zeros)"; listHelpNotation[16] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (31 Trailing Zeros)"; listHelpNotation[17] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (33 Trailing Zeros)"; listHelpNotation[18] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (35 Trailing Zeros)"; listHelpNotation[19] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (37 Trailing Zeros)"; listHelpNotation[20] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (39 Trailing Zeros)"; }; if (!String.trim) { String.trim = function (str) { var result = ""; var firstNonWhiteSpaceFound = false; var startIndex = -1; var endIndex = -1; if (str) { for (var i = 0; i < str.length; i++) { if (firstNonWhiteSpaceFound === false) { if (str[i] === ' ' || str[i] === '\t') { continue; } else { firstNonWhiteSpaceFound = true; startIndex = i; endIndex = i; } } else { if (str[i] === ' ' || str[i] === '\t') { continue; } else { endIndex = i; } } } if (startIndex !== -1 && endIndex !== -1) { result = str.slice(startIndex, endIndex + 1); } } return result; }; }

Below are the translations from

  • integer to word
  • float to word
  • money to word

Test cases are at the bottom

 var ONE_THOUSAND = Math.pow(10, 3); var ONE_MILLION = Math.pow(10, 6); var ONE_BILLION = Math.pow(10, 9); var ONE_TRILLION = Math.pow(10, 12); var ONE_QUADRILLION = Math.pow(10, 15); var ONE_QUINTILLION = Math.pow(10, 18); function integerToWord(integer) { var prefix = ''; var suffix = ''; if (!integer){ return "zero"; } if(integer < 0){ prefix = "negative"; suffix = integerToWord(-1 * integer); return prefix + " " + suffix; } if(integer <= 90){ switch (integer) { case integer < 0: prefix = "negative"; suffix = integerToWord(-1 * integer); return prefix + " " + suffix; case 1: return "one"; case 2: return "two"; case 3: return "three"; case 4: return "four"; case 5: return "five"; case 6: return "six"; case 7: return "seven"; case 8: return "eight"; case 9: return "nine"; case 10: return "ten"; case 11: return "eleven"; case 12: return "twelve"; case 13: return "thirteen"; case 14: return "fourteen"; case 15: return "fifteen"; case 16: return "sixteen"; case 17: return "seventeen"; case 18: return "eighteen"; case 19: return "nineteen"; case 20: return "twenty"; case 30: return "thirty"; case 40: return "forty"; case 50: return "fifty"; case 60: return "sixty"; case 70: return "seventy"; case 80: return "eighty"; case 90: return "ninety"; default: break; } } if(integer < 100){ prefix = integerToWord(integer - integer % 10); suffix = integerToWord(integer % 10); return prefix + "-" + suffix; } if(integer < ONE_THOUSAND){ prefix = integerToWord(parseInt(Math.floor(integer / 100), 10) ) + " hundred"; if (integer % 100){ suffix = " and " + integerToWord(integer % 100); } return prefix + suffix; } if(integer < ONE_MILLION){ prefix = integerToWord(parseInt(Math.floor(integer / ONE_THOUSAND), 10)) + " thousand"; if (integer % ONE_THOUSAND){ suffix = integerToWord(integer % ONE_THOUSAND); } } else if(integer < ONE_BILLION){ prefix = integerToWord(parseInt(Math.floor(integer / ONE_MILLION), 10)) + " million"; if (integer % ONE_MILLION){ suffix = integerToWord(integer % ONE_MILLION); } } else if(integer < ONE_TRILLION){ prefix = integerToWord(parseInt(Math.floor(integer / ONE_BILLION), 10)) + " billion"; if (integer % ONE_BILLION){ suffix = integerToWord(integer % ONE_BILLION); } } else if(integer < ONE_QUADRILLION){ prefix = integerToWord(parseInt(Math.floor(integer / ONE_TRILLION), 10)) + " trillion"; if (integer % ONE_TRILLION){ suffix = integerToWord(integer % ONE_TRILLION); } } else if(integer < ONE_QUINTILLION){ prefix = integerToWord(parseInt(Math.floor(integer / ONE_QUADRILLION), 10)) + " quadrillion"; if (integer % ONE_QUADRILLION){ suffix = integerToWord(integer % ONE_QUADRILLION); } } else { return ''; } return prefix + " " + suffix; } function moneyToWord(value){ var decimalValue = (value % 1); var integer = value - decimalValue; decimalValue = Math.round(decimalValue * 100); var decimalText = !decimalValue? '': integerToWord(decimalValue) + ' cent' + (decimalValue === 1? '': 's'); var integerText= !integer? '': integerToWord(integer) + ' dollar' + (integer === 1? '': 's'); return ( integer && !decimalValue? integerText: integer && decimalValue? integerText + ' and ' + decimalText: !integer && decimalValue? decimalText: 'zero cents' ); } function floatToWord(value){ var decimalValue = (value % 1); var integer = value - decimalValue; decimalValue = Math.round(decimalValue * 100); var decimalText = !decimalValue? '': decimalValue < 10? "point o' " + integerToWord(decimalValue): decimalValue % 10 === 0? 'point ' + integerToWord(decimalValue / 10): 'point ' + integerToWord(decimalValue); return ( integer && !decimalValue? integerToWord(integer): integer && decimalValue? [integerToWord(integer), decimalText].join(' '): !integer && decimalValue? decimalText: integerToWord(0) ); } // test (function(){ console.log('integerToWord =================================='); for(var i = 0; i < 101; ++i){ console.log('%s=%s', i, integerToWord(i)); } console.log('floatToWord ===================================='); i = 131; while(i--){ console.log('%s=%s', i / 100, floatToWord(i / 100)); } console.log('moneyToWord ===================================='); for(i = 0; i < 131; ++i){ console.log('%s=%s', i / 100, moneyToWord(i / 100)); } }()); 

Another conversion that uses remainders and supports different languages:

 function numberToWords(number) { var result = []; var fraction = number.toFixed(2).split('.'); var integer_part = parseInt(fraction[0]); // var fractional_part = parseInt(fraction[1]); -- not handled here var previousNumber = null; for (var i = 0; i < fraction[0].length; i++) { var reminder = Math.floor(integer_part % 10); integer_part /= 10; var name = getNumberName(reminder, i, fraction[0].length, previousNumber); previousNumber = reminder; if (name) result.push(name); } result.reverse(); return result.join(' '); } 

The getNumberName function is language-dependent and handles numbers up to 9999 (but it is easy to extend it to handle larger numbers):

 function getNumberName(number, power, places, previousNumber) { var result = ""; if (power == 1) { result = handleTeensAndTys(number, previousNumber); } else if (power == 0 && places != 1 || number == 0) { // skip number that was handled in teens and zero } else { result = locale.numberNames[number.toString()] + locale.powerNames[power.toString()]; } return result; } 

handleTeensAndTys handles multiples of ten:

 function handleTeensAndTys(number, previousNumber) { var result = ""; if (number == 1) { // teens if (previousNumber in locale.specialTeenNames) { result = locale.specialTeenNames[previousNumber]; } else if (previousNumber in locale.specialTyNames) { result = locale.specialTyNames[previousNumber] + locale.teenSuffix; } else { result = locale.numberNames[previousNumber] + locale.teenSuffix; } } else if (number == 0) { // previousNumber was not handled in teens result = locale.numberNames[previousNumber.toString()]; } else { // other tys if (number in locale.specialTyNames) { result = locale.specialTyNames[number]; } else { result = locale.numberNames[number]; } result += locale.powerNames[1]; if (previousNumber != 0) { result += " " + locale.numberNames[previousNumber.toString()]; } } return result; } 

Finally, locale examples:

 var locale = { // English numberNames: {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine" }, powerNames: {0: "", 1: "ty", 2: " hundred", 3: " thousand" }, specialTeenNames: {0: "ten", 1: "eleven", 2: "twelve" }, specialTyNames: {2: "twen", 3: "thir", 5: "fif" }, teenSuffix: "teen" }; var locale = { // Estonian numberNames: {1: "üks", 2: "kaks", 3: "kolm", 4: "neli", 5: "viis", 6: "kuus", 7: "seitse", 8: "kaheksa", 9: "üheksa"}, powerNames: {0: "", 1: "kümmend", 2: "sada", 3: " tuhat" }, specialTeenNames: {0: "kümme"}, specialTyNames: {}, teenSuffix: "teist" }; 

Here's a JSFiddle with tests: https://jsfiddle.net/rcrxna7v/15/

You can check my version from github. It is not so hard way. I test this for the numbers between 0 and 9999, but you can extend array if you would like digits to words

If you need with Cent then you may use this one

     

js violino

Here taka mean USD and paisa mean cent

This is also in response to naomik’s excellent post ! Unfortunately I don’t have the rep to post in the correct place but I leave this here in case it can help anyone.

If you need British English written form you need to make some adaptions to the code. British English differs from the American in a couple of ways. Basically you need to insert the word ‘and’ in two specific places.

  1. After a hundred assuming there are tens and ones. Eg One hundred and ten. One thousand and seventeen. NOT One thousand one hundred and.
  2. In certain edges, after a thousand, a million, a billion etc . when there are no smaller units. Eg One thousand and ten. One million and forty four. NOT One million and one thousand.

The first situation can be addressed by checking for 10s and 1s in the makeGroup method and appending ‘and’ when they exist.

 makeGroup = ([ones,tens,huns]) => { var adjective = this.num(ones) ? ' hundred and ' : this.num(tens) ? ' hundred and ' : ' hundred'; return [ this.num(huns) === 0 ? '' : this.a[huns] + adjective, this.num(ones) === 0 ? this.b[tens] : this.b[tens] && this.b[tens] + '-' || '', this.a[tens+ones] || this.a[ones] ].join(''); 

};

The second case is more complicated. It is equivalent to

  • add ‘and’ to ‘a million, a thousand’, or ‘a billion’ if the antepenultimate number is zero. por exemplo

1,100, 0 57 one million one hundred thousand and fifty seven. 5,000, 0 06 five million and six

I think this could be implemented in @naomik’s code through the use of a filter function but I wasn’t able to work out how. In the end I settled on hackily looping through the returned array of words and using indexOf to look for instances where the word ‘hundred’ was missing from the final element.

I’ve just written paisa.js to do this, and it handles lakhs and crores correctly as well, can check it out. The core looks a bit like this:

 const regulars = [ { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine' }, { 2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety' } ] const exceptions = { 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen' } const partInWords = (part) => { if (parseInt(part) === 0) return const digits = part.split('') const words = [] if (digits.length === 3) { words.push([regulars[0][digits.shift()], 'hundred'].join(' ')) } if (exceptions[digits.join('')]) { words.push(exceptions[digits.join('')]) } else { words.push(digits.reverse().reduce((memo, el, i) => { memo.unshift(regulars[i][el]) return memo }, []).filter(w => w).join(' ')) } return words.filter(w => w.trim().length).join(' and ') } 

Lot of good answers. I needed mine for Indian (South Asian) numbering system. I modified one of the codes above – attaching it here, in case, someone else needs this. In the Indian numbering system, groups after thousands are in in 2 digits, not 3 as in the western system.

 var IS_SOUTH_ASIAN = true; function int_to_words(int) { if (int === 0) return 'zero'; var ONES_WORD = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']; var TENS_WORD = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']; var SCALE_WORD_WESTERN = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion']; var SCALE_WORD_SOUTH_ASIAN = ['','thousand','lakh','crore','arab','kharab','neel','padma','shankh','***','***']; var GROUP_SIZE = (typeof IS_SOUTH_ASIAN != "undefined" && IS_SOUTH_ASIAN) ? 2 : 3; var SCALE_WORD = (typeof IS_SOUTH_ASIAN != "undefined" && IS_SOUTH_ASIAN) ? SCALE_WORD_SOUTH_ASIAN : SCALE_WORD_WESTERN; // Return string of first three digits, padded with zeros if needed function get_first_3(str) { return ('000' + str).substr(-(3)); } function get_first(str) { //-- Return string of first GROUP_SIZE digits, padded with zeros if needed, if group size is 2, make it size 3 by prefixing with a '0' return (GROUP_SIZE == 2 ? '0' : '') + ('000' + str).substr(-(GROUP_SIZE)); } // Return string of digits with first three digits chopped off function get_rest_3(str) { return str.substr(0, str.length - 3); } function get_rest(str) { // Return string of digits with first GROUP_SIZE digits chopped off return str.substr(0, str.length - GROUP_SIZE); } // Return string of triplet convereted to words function triplet_to_words(_3rd, _2nd, _1st) { return (_3rd == '0' ? '' : ONES_WORD[_3rd] + ' hundred ') + (_1st == '0' ? TENS_WORD[_2nd] : TENS_WORD[_2nd] && TENS_WORD[_2nd] + '-' || '') + (ONES_WORD[_2nd + _1st] || ONES_WORD[_1st]); //-- 1st one returns one-nineteen - second one returns one-nine } // Add to result, triplet words with scale word function add_to_result(result, triplet_words, scale_word) { return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + result : result; } function recurse (result, scaleIdx, first, rest) { if (first == '000' && rest.length === 0) return result; var newResult = add_to_result (result, triplet_to_words (first[0], first[1], first[2]), SCALE_WORD[scaleIdx]); return recurse (newResult, ++scaleIdx, get_first(rest), get_rest(rest)); } return recurse ('', 0, get_first_3(String(int)), get_rest_3(String(int))); } 

Try this code with a Turkish currency compliant JavaScript

 function dene() { var inpt = document.getElementById("tar1").value; var spt = inpt.split(''); spt.reverse(); var tek = ["", "Bir", "İki", "Üç", "Dört", "Beş", "Altı", "Yedi", "Sekiz", "Dokuz"]; var onlu = ["", "On", "Yirmi", "Otuz", "Kırk", "Elli", "Atmış", "Yetmiş", "Seksen", "Doksan"]; var Yuz = ["", "Yüz", "İkiYüz", "Üçyüz", "DörtYüz", "BeşYüz", "AltıYüz", "YediYüz", "SekizYüz", "DokuzYüz"]; var ska = ["", "", "", "", "Bin", "Milyon", "Milyar", "Trilyon", "Katrilyon", "Kentilyon"]; var i, j; var bas3 = ""; var bas6 = ""; var bas9 = ""; var bas12 = ""; var total; for(i = 0; i < 1; i++) { bas3 += Yuz[spt[i+2]] + onlu[spt[i+1]] + tek[spt[i]]; bas6 += Yuz[spt[i+5]] + onlu[spt[i+4]] + tek[spt[i+3]] + ska[4]; bas9 += Yuz[spt[i+8]] + onlu[spt[i+7]] + tek[spt[i+6]] + ska[5]; bas12 += Yuz[spt[i+11]] + onlu[spt[i+10]] + tek[spt[i+9]] + ska[6]; if(inpt.length < 4) { bas6 = ''; bas9 = ''; } if(inpt.length > 6 && inpt.slice(5, 6) == 0) { bas6 = bas6.replace(/Bin/g, ''); } if(inpt.length < 7) { bas9 = ''; } if(inpt.length > 9 && inpt.slice(1,3) == 000){ bas9 = bas9.replace(/Milyon/g, ''); } if(inpt.length < 10) { bas12 = ''; } } total = bas12 + bas9 + bas6 + bas3; total = total.replace(NaN, ''); total = total.replace(undefined, ''); document.getElementById('demo').innerHTML = total; }