JavaScript数字金额转换成中文大写展示

本文介绍了一种使用JavaScript将数字金额转换为中文大写显示的方法。通过定义数字和单位对应的字符数组,函数能够处理整数和小数部分,实现金额的精确转换,并在末尾添加“整”字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// JavaScript数字金额转换成中文大写显示
function moneyToString(num) {
    const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    const radices =['', '拾', '佰', '仟', '万', '亿'];
    const bigRadices = ['', '万', '亿'];
    const decimals = ['角', '分']; // 这里只精确到分
    const cn_dollar = '元';
    const cn_integer = '整';
    // int_str = Math.floor(num).toString();
    // float_str = num % 1;
    const num_arr = num.toString().split('.');
    const int_str = num_arr[0] || '';
    let float_str = num_arr[1] || '';
    if (float_str.length > 2) {
        float_str = float_str.substr(0, 2);
    }
    let outputCharacters = '';
    if (int_str) {
        let zeroCount = 0;
        const int_len = int_str.length;
        for (var i = 0; i < int_len; i++) {
            const p = int_len - i - 1;
            d = int_str.substr(i, 1);
            const quotient = p / 4;
            modulus = p % 4;
            if (d === '0') {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    outputCharacters += digits[0];
                }
                zeroCount = 0;
                outputCharacters += digits[d] + radices[modulus];
            }
            if (modulus === 0 && zeroCount < 4) {
                outputCharacters += bigRadices[quotient];
                zeroCount = 0;
            }
        }
        outputCharacters += cn_dollar;
    }

    if (float_str) {
        const float_len = float_str.length;
        for (let i = 0; i < float_len; i++) {
            const d = float_str.substr(i, 1);
            if (d !== '0') {
                outputCharacters += digits[d] + decimals[i];
            }          
        }
    }

    if (outputCharacters === '') {
        outputCharacters = digits[0] + cn_dollar;
    }

    if (float_str) {
        outputCharacters += cn_integer;
    }

    return outputCharacters;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值