js将阿拉伯数字转换为大写中文金额

这段代码实现了一个将数字字符串转换为中文大写金额的函数,包括了小数点前后的转换规则,适用于财务或会计领域的数据处理。

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

moneyToCaptital = (money: string) => {
		//将小数点前后划分开
        const dots=money.split('.')
        const dotFor=dots[0]
        const dotBehind=dots[1]
        //小数点前一部分,先反转一下,如'123'变成‘321’
        money = dotFor.split('').reverse().join('')
        const cap = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖")
        const unit = new Array("", "拾", "佰", "仟")
        const lunit = new Array("", "万", "亿", "兆")
        const len = money.length
        const level = Math.ceil(len / 4)
        let res = ''
        //每4位数作为一次计算,如'1234444'读作一百二十三万四千四百四十四,反转后变为4444,321,从后开始往前计算
        for (let i = level - 1; i >= 0; --i) {
            let hasZero = false//用一个hasZero变量控制0的读法
            for (let k = 3; k >= 0; --k) {
                let cur = +i * 4 + k
                if (cur < len) {
                	//如果0在中间或前面,读出来,如果在后面不读出来
                	//如果有多个0在前面或中间,只读一个
                    if (money[cur] == '0') hasZero = true//遇到0先不读出
                    else {//遇到0之后的第一个非0数字证明0在中间位置,需要读出来
                        if (hasZero) {
                            res += '零'
                        }
                        res += cap[+money[cur]] + ''
                        res += unit[cur % 4] + ''
                    }
                }
            }
            res += lunit[i]
        }
        res+='元'
        //小数点后面,只考虑两位数角和分
        if(dotBehind){
            const dot0:string=dotBehind[0]
            const dot1:string=dotBehind[1]
            if(dot0=='0'){
                if(dot1&&dot1!='0') res+=cap[+dot0]+'角'+cap[+dot1]+'分'
                else res+=cap[+dot0]+'角'
            }else{
                if(dot1&&dot1!='0') res+='零角'+cap[+dot1]+'分'
            }
        }
       
        console.log('res', res)
        return res
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值