How to convert number to words in javascript
In this post we will show you convert number to words in javascript, hear for convert number to words in javascript we will give you demo and example for implement.
If you are writing an application that deals with financial stuffs, then most probably you will come to a situation where you would have to convert numerical values to words Example: to write the amounts in words
File Create File Name with numbertowordconvertconvert.js
// System for American Numbering var th_val = ['', 'thousand', 'million', 'billion', 'trillion']; // System for uncomment this line for Number of English // var th_val = ['','thousand','million', 'milliard','billion']; var dg_val = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; var tn_val = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']; var tw_val = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']; function toWordsconver(s) { s = s.toString(); s = s.replace(/[\, ]/g, ''); if (s != parseFloat(s)) return 'not a number '; var x_val = s.indexOf('.'); if (x_val == -1) x_val = s.length; if (x_val > 15) return 'too big'; var n_val = s.split(''); var str_val = ''; var sk_val = 0; for (var i = 0; i < x_val; i++) { if ((x_val - i) % 3 == 2) { if (n_val[i] == '1') { str_val += tn_val[Number(n_val[i + 1])] + ' '; i++; sk_val = 1; } else if (n_val[i] != 0) { str_val += tw_val[n_val[i] - 2] + ' '; sk_val = 1; } } else if (n_val[i] != 0) { str_val += dg_val[n_val[i]] + ' '; if ((x_val - i) % 3 == 0) str_val += 'hundred '; sk_val = 1; } if ((x_val - i) % 3 == 1) { if (sk_val) str_val += th_val[(x_val - i - 1) / 3] + ' '; sk_val = 0; } } if (x_val != s.length) { var y_val = s.length; str_val += 'point '; for (var i = x_val + 1; i < y_val; i++) str_val += dg_val[n_val[i]] + ' '; } return str_val.replace(/\s+/g, ' '); }
To use this javascript library, all you need to do is select all the code and save it in a file numbertowordconvert.js and use it as follows:
// numbertowordconvert.js for Import the javascript file: <script type="text/javascript" src="numbertowordconvert.js"></script> // Call the function toWordsconver(number) passing a number to it: <script> var number = 1525; var Inwords = toWordsconver(number); </script>
Hope this code and post will helped you for implement convert number to words in javascript”. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve onlincode. we will give you this type of more interesultting post in featured also so, For more interesultting post and code Keep reading our blogs onlincode.org
A jsfiddle demo would have been helpful
thanks for feedback, https://jsfiddle.net/25ys0vpj/
Wow, thank you so much. I have been looking for this, for a long time. I appreciate your effort.