Home >Web Front-end >JS Tutorial >How to Convert Numbers to Words Using the Lakh/Crore System?
Transforming Numbers to Words in the Lakh/Crore System
You're trying to convert numbers into words, specifically following the South Asian numbering system, known as the lakh and crore system. Unfortunately, the code you've written currently utilizes the English numbering system, using terms like "million" and "billion."
To achieve your desired result, you can opt for a simpler approach with fewer lines of code. Here's a concise and efficient version:
<code class="js">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; }</code>
This improved code provides several notable benefits:
Here's a live example you can use to test the code:
<code class="html"><span id="words"></span> <input id="number" type="text" /></code>
<code class="js">document.getElementById('number').onkeyup = function () { document.getElementById('words').innerHTML = inWords(document.getElementById('number').value); };</code>
By incorporating this code into your project, you can efficiently and accurately convert numbers to words in the lakh and crore system. Let us know if you have any further questions or require any assistance.
The above is the detailed content of How to Convert Numbers to Words Using the Lakh/Crore System?. For more information, please follow other related articles on the PHP Chinese website!