当前位置: 首页 > article >正文

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

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

代码

<!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>


http://www.kler.cn/news/342916.html

相关文章:

  • xml文件格式样例
  • 《网络基础之 HTTP 协议:状态码含义全解析》
  • 滚雪球学Redis[2.2讲]:列表(List)
  • 户外足球运动人像自拍摄影后期Lr调色教程,手机滤镜PS+Lightroom预设下载!
  • Leetcode 完全平方数
  • TypeScript 中命名空间与模块的理解及区别
  • 美化pytest运行:pytest-sugar
  • 11.Lab Ten —— mmap
  • 《自然语言处理NLP》—— 独热编码(One-Hot Encoding)
  • 华为 HCIP-Datacom H12-821 题库 (35)
  • Docker安装Nginx
  • 在python中如何判断回文串(一)?
  • 设计模式01-类图及设计原理(Java)
  • Golang | Leetcode Golang题解之第456题132模式
  • 为何一个简单的线上商城 两年销售7000多万?
  • 如何在uniAPP中编写页面
  • SFML库环境配置
  • Spring 如何加载多份配置文件
  • C++ | Leetcode C++题解之第468题验证IP地址
  • 奥普思凯 ——AI 扫描仪引领办公新潮流