将十亿卢比系统中的数字转换为单词:一种有效的方法
将数字转换为单词是编程中的一项常见任务,特别是在编程中财务或会计应用程序。虽然许多现有解决方案涉及具有多个正则表达式和循环的复杂代码,但本文提出了一种针对南亚编号系统的特定要求量身定制的简化方法。
该系统利用“十万”和“千万”的概念” 来表示大数。十万代表十万,一千万代表一千万。与使用逗号作为分隔符的西方编号系统不同,南亚系统使用空格。
为了有效地实现此转换,以下代码片段采用单个正则表达式并消除了循环的需要:
const a = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
const 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;
let 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;
}
````
This code combines pre-defined arrays 'a' and 'b' to form various numerical representations. By utilizing a regular expression, it captures the different sections of the number (e.g., crores, lakhs, thousands, hundreds, and ones) and generates the appropriate words. Importantly, this approach is much more concise than the earlier solution presented.
To demonstrate the code's functionality, an HTML/JavaScript snippet can be used:
document.getElementById('number').onkeyup = function () {
document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3