This JavaScript code snippet helps you to a number of words. It defines several functions that are used for preparing numbers in English and Russian languages to be used in a currency conversion program. The first function, “enHundredsPrepare,” prepares a number that is more than 100 by splitting the number into hundreds, tens, and ones, and using the corresponding English words for each place value. The function “enThreesPrepare” splits the number into groups of three digits from right to left, calls the enHundredsPrepare function for each group, and then concatenates the results to form the final English word for the number. The function “enDollarPrepare” uses the enThreesPrepare function to prepare the dollar amount for the English language, along with the corresponding currency symbol. The function “enCentsPrepare” prepares the cents amount in the same way.
Finally, the functions “ruHundredsPrepare,” “ruGettingEnds,” and “ruThreesPrepare” perform similar operations, but for the Russian language. The “ruDollarPrepare” and “ruCentsPrepare” functions are used to prepare the dollar and cents amounts for the Russian language, respectively.
How to Create Convert Number To Words JavaScript
First of all, load the following assets into the head tag of your HTML document.
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css'>
Create the HTML structure for the number to words as follows:
<div class="num-to-word-block"> <div class="num-to-word-input"> <label> <span>Number</span> <input id="num" type="text" name="number" placeholder="Enter num here" maxlength="12"/> </label> <label> <input class="currency" type="radio" name="currency" value="0" checked="checked"/><span><i class="fas fa-dollar-sign"> </i></span> </label> <label> <input class="currency" type="radio" name="currency" value="1"/><span><i class="fas fa-euro-sign"> </i></span> </label> <label> <input class="currency" type="radio" name="currency" value="2"/><span><i class="fas fa-pound-sign"> </i></span> </label> <label> <input class="currency" type="radio" name="currency" value="3"/><span><i class="fas fa-ruble-sign"> </i></span> </label> </div> <div class="num-to-word-convert"> <p class="num-to-word-converter-english"><span>english</span><span></span></p> <button class="num-copy num-to-word-converter-copy-english"><i class="far fa-copy"></i></button> <p class="num-to-word-converter-russian"><span>russian</span><span></span></p> <button class="num-copy num-to-word-converter-copy-russian"><i class="far fa-copy"></i></button> </div> </div>
Now, style the number to words using the following CSS styles:
* { box-sizing: border-box; } body { background: gray; color: white; margin: 0; padding: 50px 0; width: 100%; min-height: 100vh; text-align: center; box-sizing: border-box; } .num-to-word-block { display: inline-block; width: 500px; padding: 50px; background: darkslateblue; border: 1px solid black; } .num-to-word-block label:nth-child(1) { display: block; position: relative; } .num-to-word-block label:nth-child(1) span { display: block; text-align: left; text-transform: uppercase; } .num-to-word-block label:nth-child(1)::after { display: block; content: ""; position: absolute; bottom: -2px; right: 0; width: 100%; height: 2px; background: white; } .num-to-word-block input[name=number] { width: 300px; border: none; font-size: 20pt; text-align: right; background-color: darkslateblue; color: gold; } .num-to-word-block input[name=number]:active { background-color: darkslateblue; border: none; } .num-to-word-block input[type=radio] { display: none; } .num-to-word-block input[type=radio] + span { margin: 10px -2px; display: inline-block; padding: 30px; position: relative; } .num-to-word-block input[type=radio] + span::after { content: ""; display: block; position: absolute; bottom: -2px; right: 0; height: 2px; width: 0; background: gold; transition: all 0.5s ease-out; } .num-to-word-block input[type=radio] + span i { font-size: 20pt; } .num-to-word-block input[type=radio]:checked + span i { color: gold; } .num-to-word-block input[type=radio]:checked + span::after { width: 100%; } .num-to-word-convert p { text-align: left; } .num-to-word-convert p span:nth-child(1) { text-transform: uppercase; } .num-to-word-convert p span:nth-child(2) { display: block; height: 70px; width: 100%; border: 1px solid white; padding: 5px 10px; font-size: 14pt; color: #FF006F; } .num-to-word-convert p span:nth-child(2):first-letter { text-transform: uppercase; } .num-copy { width: 100%; cursor: pointer; } .num-copy i { font-size: 20pt; color: darkslateblue; }
Load the following scripts before closing the body tag:
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
Finally, add the following JavaScript function for its functionality:
let numEnglish = [ ['zero'], ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'], ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'], ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'], ['hundred'], ['', 'thousand', 'million', 'billion'] ]; let numRussian = [ ['ноль','одна','две'], ['', 'один', 'два', 'три', 'четыре', 'пять', 'шесть', 'семь', 'восемь', 'девять'], ['десять', 'одиннадцать', 'двенадцать', 'тринадцать', 'четырнадцать', 'пятнадцать', 'шестнадцать', 'семнадцать', 'восемнадцать', 'девятнадцать'], ['', 'десять', 'двадцать', 'тридцать', 'сорок', 'пятьдесят', 'шестьдесят', 'семьдесят', 'восемьдесят', 'девяносто'], ['', 'сто', 'двести', 'триста', 'четыреста', 'пятьсот', 'шестьсот','семьсот', 'восемьсот', 'девятьсот'], [['','',''],['тысяча', 'тысячи', 'тысяч'], ['миллион', 'миллиона', 'миллионов'], ['миллард', 'милларда', 'миллардов']] ]; let currencyEnglish = [['dollar', 'euro', 'pound', 'ruble'], ['cent', 'cent', 'cent', 'kopeika']]; let currencyRussian = [[['доллар США', 'доллара США', 'долларов США'], ['евро', 'евро', 'евро'], ['фунт стерлингов', 'фунта стерлингов', 'фунтов стерглингов'], ['рубль', 'рубля', 'рублей']], [['цент', 'цента', 'центов'], ['цент', 'цента', 'центов'], ['цент', 'цента', 'центов'], ['копейка', 'копейки', 'копеек']]]; let mistakes = [['incorrect value'], ['неправильный ввод']]; // text validation let validateNumber= function(str){ return ((/^[0-9,.\s]+$/).test(str)); }; // text publishing let publishWordsNumber = function(strEn, strRu){ $('.num-to-word-converter-english span').eq(1).text(strEn); $('.num-to-word-converter-russian span').eq(1).text(strRu); } // en prepare number for hundreds let enHundredsPrepare = function(str){ let txt= ''; // prepare num more than 100 if(+str>99){ txt = numEnglish[1][Math.floor((+str)/100)] +" " + numEnglish[4][0]+ " "; str = str.substring(1); } // prepare num more than 19 and less than 100 if((+str)>19){ txt += numEnglish[3][Math.floor((+str)/10)] + " "; str = str.substring(1); } // prepare num more than 9 and less than 20 if((+str)<20&(+str)>9){ txt += numEnglish[2][+str-10]; } // prepare num less than 10 if(+str<10 & +str!=0){ txt += numEnglish[1][str]; } return txt; }; // en prepare threes let enThreesPrepare = function(str){ let txt=''; // split string to three numbers from end to start let charsLength = str.length; let chunks = []; for (let i = charsLength ; i > 0; i -= 3) { chunks.push(str.substring(i - 3, i)); } // add three numbers place () charsLength = chunks.length; for(let j = 0; j < charsLength; j++){ txt = enHundredsPrepare(chunks[j]) + " " + numEnglish[5][j] + " " + txt; } return txt; } // en prepare dollars let enDollarPrepare = function(str){ if(+str == 0){ return (numEnglish[0][0]+' '+ currencyEnglish[0][$('input:radio:checked').val()]); } let endOfString = ''; if (+str>1){ endOfString ='s'; } let txt = enThreesPrepare(str); return ('' +txt+' '+ currencyEnglish[0][$('input:radio:checked').val()] + endOfString); } // en prepare sums of cents let enCentsPrepare = function(str){ let endOfString = ''; if (+str>1){ endOfString ='s'; } return ('' +str+' '+ currencyEnglish[1][$('input:radio:checked').val()] + endOfString); }; // ru prepare number for hundreds let ruHundredsPrepare = function(str, thosands){ let txt= ''; // prepare num more than 100 if(+str>99){ txt = numRussian[4][Math.floor((+str)/100)] +" "; str = str.substr(1); } // prepare num more than 19 and less than 100 if((+str)>19){ txt += numRussian[3][Math.floor((+str)/10)] + " "; str = str.substr(1); } // prepare num more than 9 and less than 20 if((+str)<20&(+str)>9){ txt += numRussian[2][+str-10]; } // prepare num less than 10 if(+str<10 & +str!=0){ if(thosands==1 & +str==2){ txt += numRussian[0][2]; } else if(thosands==1 & +str==1){ txt += numRussian[0][1]; }else{ txt += numRussian[1][str]; } } return txt; }; //gettings ends let ruGettingEnds = function(str, thosands){ if (+str>99){ str = str.substr(-2); } if(+str<20 & +str>9){ return 2; } if(+str>10){ str = str.substr(1); } if(+str==1){ return 0; } if(+str>1 & +str<5){ return 1; } return 2; } // ru prepare threes let ruThreesPrepare = function(str){ let txt=''; let n = 0; // split string to three numbers from end to start let charsLength = str.length; let chunks = []; for (let i = charsLength ; i > 0; i -= 3) { chunks.push(str.substring(i - 3, i)); } // add three numbers place () charsLength = chunks.length; for(let j = 0; j < charsLength; j++){ n = 0; n = ruGettingEnds(chunks[j], j); txt = ruHundredsPrepare(chunks[j], j) + " " + numRussian[5][j][n] + " " + txt; } return txt; } // ru prepare sums of dollars let ruDollarPrepare = function(str){ if(+str == 0){ return (numRussian[0][0]+' '+ currencyRussian[0][$('input:radio:checked').val()][2]) } let n = ruGettingEnds(str, 0); return ('' +ruThreesPrepare(str)+' '+ currencyRussian[0][$('input:radio:checked').val()][n]); }; // ru prepare sums of cents let ruCentsPrepare = function(str){ let num = 2; if (!((+str)>9 & (+str)<20)){ if((''+str)[1]=='1'){ num = 0; } else if ((''+str)[1]=='2' || (''+str)[1]=='3' || (''+str)[1]=='4'){ num = 1; } } return ('' +str+' '+ currencyRussian[1][$('input:radio:checked').val()][num]); }; // getting answer let numGetting = function (){ str = $('#num').val(); if (!validateNumber(str) || str.length >12){ // if there are any unexpected symbols - return mistake answerEn = mistakes[0][0]; answerRu = mistakes[1][0]; }else{ // clear superfluous symbols str = str.replace(/\s/g,""); str = str.replace(/,/g,"."); str = str.replace(/(.*)\./, x => x.replace(/\./g,'')+'.'); str = Math.round(((+str)*100))/100; let valueCurrency = (""+str).split('.'); if (valueCurrency.length<2){ valueCurrency[1] = '00' } else if (valueCurrency[1].length<2){ valueCurrency[1] = "" + valueCurrency[1] + "0"; } str = ''+valueCurrency[0]+"."+valueCurrency[1]; // update input $('#num').val(str); // answers here answerEn = enDollarPrepare(valueCurrency[0]) + " " + enCentsPrepare(valueCurrency[1]); answerRu = ruDollarPrepare(valueCurrency[0]) + " " + ruCentsPrepare(valueCurrency[1]); answerEn = answerEn[0].toUpperCase() + answerEn.slice(1); answerRu = answerRu[0].toUpperCase() + answerRu.slice(1); } publishWordsNumber(answerEn, answerRu); }; // update after inputs of number $('#num').change(function(){ numGetting(); }); // update after inputs of currency $('.currency').change(function(){ numGetting(); }); // add text to clipBoard let addToClipBoard = function(str){ const clpBoard = document.createElement('textarea'); clpBoard.value = str; clpBoard.setAttribute('readonly', ''); clpBoard.style.position = 'absolute'; clpBoard.style.left = '-9999px'; document.body.appendChild(clpBoard); clpBoard.select(); document.execCommand('copy'); document.body.removeChild(clpBoard); } // select English text for coping to clipboard $('.num-to-word-converter-copy-english').click(function(){ addToClipBoard($('.num-to-word-converter-english span').eq(1).text()); }); // select Russian text for coping to clipboard $('.num-to-word-converter-copy-russian').click(function(){ addToClipBoard($('.num-to-word-converter-russian span').eq(1).text()); });
That’s all! hopefully, you have successfully created the JavaScript convert number to words. If you have any questions or suggestions, feel free to comment below.