將十萬/千萬系統中的數字轉換為單字:一種有效的方法
將數字轉換為單字是程式設計中的一項常見任務,尤其是在程式設計中財務或會計應用程式。雖然許多現有解決方案涉及具有多個正規表示式和循環的複雜程式碼,但本文提出了一種針對南亞編號系統的特定要求量身定制的簡化方法。
系統利用「十萬」和「千萬」的概念」 來表示大數。十萬代表十萬,一千萬代表一千萬。與使用逗號作為分隔符號的西方編號系統不同,南亞系統使用空格。 ').onkeyup = function () {
};<code class="javascript">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: </code>
document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
以上是如何有效地將十萬千萬系統中的數字轉換為單字?的詳細內容。更多資訊請關注PHP中文網其他相關文章!