【工具】前端js数字金额转中文大写金额

【工具】前端js数字金额转中文大写金额_javascript

【工具】前端js数字金额转中文大写金额_前端_02

代码

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>金额转大写</title>
    <style>
        input {
            margin: 5px;
            padding: 10px;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <h1>金额转大写</h1>
    <label for="amount">输入金额(整数或小数):</label>
    <input type="text" id="amount" placeholder="请输入金额" oninput="convertToChinese()" />
    <br />
    <label for="amountInWords">大写金额:</label>
    <input type="text" id="amountInWords" readonly />
    
    <script>
        function convertToChinese() {
            const amountInput = document.getElementById('amount');
            const amountInWords = document.getElementById('amountInWords');
            const amount = parseFloat(amountInput.value);

            if (!isNaN(amount)) {
                amountInWords.value = toChinaNum(amount);
            } else {
                amountInWords.value = '';
            }
        }

        function toChinaNum(number) {
            if (isNaN(number) || !isFinite(number)) {
                throw new Error('传值错误');
            }
            const fraction = ['角', '分'];
            const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
            const unit = [
                ['元', '万', '亿'],
                ['', '拾', '佰', '仟']
            ];
            let num = Math.abs(number);
            let s = '';
            const decimalPart = Math.floor((num * 100) % 100);
            fraction.forEach((item, index) => {
                s += (digit[Math.floor(decimalPart / (10 ** (1 - index))) % 10] + item).replace(/零./, '');
            });
            s = s || '';
            num = Math.floor(num);
            for (let i = 0; i < unit[0].length && num > 0; i += 1) {
                let p = '';
                for (let j = 0; j < unit[1].length && num > 0; j += 1) {
                    p = digit[num % 10] + unit[1][j] + p;
                    num = Math.floor(num / 10);
                }
                s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
            }
            return s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^元$/, '零元');
        }

    </script>
</body>
</html>