Home  >  Article  >  Web Front-end  >  How to Convert Numbers to Lakhs and Crores in JavaScript?

How to Convert Numbers to Lakhs and Crores in JavaScript?

DDD
DDDOriginal
2024-11-06 16:54:03156browse

How to Convert Numbers to Lakhs and Crores in JavaScript?

Converting Numbers to Lakhs/Crores

As a developer, encountering the task of converting numbers into words often arises. While existing code options may seem lengthy, this article aims to present a more concise approach.

Existing Method

The given code employs regular expressions and loops for word conversion:

<code class="javascript">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) { ... }</code>

South Asian Numbering System

However, this code converts numbers using the Western numbering system (millions/billions). To adapt it for the South Asian system (lakhs/crores), modifications are necessary.

Concise Code

The following code offers a streamlined solution:

<code class="javascript">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 revised code converts numbers to words in the South Asian numbering system, accounting for lakhs and crores.

The above is the detailed content of How to Convert Numbers to Lakhs and Crores in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn