Python实现将数字转换为大写中文

实现代码一

代码较为简洁,原文链接:https://www.jianshu.com/p/9aeba09cf71e

import re
from decimal import Decimal, ROUND_HALF_UP

ZH_HANS_MAP = dict(zip(range(10), "零壹贰叁肆伍陆柒捌玖"))

def verbose_price(cost):
    cost = Decimal(cost).quantize(Decimal('0.00'), ROUND_HALF_UP)   # 四舍五入保留两位小数
    if cost >= 100_000_000:
        return "大于等于1亿"
    if cost >= 10000:
        w = int(cost // 10000)
        rest = int(cost % 10000)
        r = qian(w) + "万" + qian(rest)
    elif cost >= 1:
        r = qian(int(cost))
    else:
        r = ""
    if r:
        r += "圆"
    if int(cost) == cost:
        r += "整"
    else:
        j, f = int(cost * Decimal(10)) % 10, int(cost * Decimal(100)) % 10
        t = ZH_HANS_MAP[j] + "角" * bool(j) + ZH_HANS_MAP[f] + "分" * bool(f)
        t = t.rstrip("零")
        if not r:
            t = t.lstrip("零")
        r += t
    return re.sub(r"零{2,}", "零", r.strip("零"))

def qian(c):
    ds = [int(i) for i in list(f"{c:04}")]
    ts = list("仟佰拾") + [""]
    s = "".join(ZH_HANS_MAP[d] + t * bool(d) for d, t in zip(ds, ts))
    return s.rstrip("零")
    
print(verbose_price(5665))

实现代码2

原文链接:https://www.jianshu.com/p/a55ac7f148ee
原文代码有一些不完善,因此在最后加了一点替换处理

import re
def digital_to_chinese(digital):
    str_digital = str(digital)
    chinese = {'1': '壹', '2': '贰', '3': '叁', '4': '肆', '5': '伍', '6': '陆', '7': '柒', '8': '捌', '9': '玖', '0': '零'}
    chinese2 = ['拾', '佰', '仟', '万', '厘', '分', '角']
    jiao = ''
    bs = str_digital.split('.')
    yuan = bs[0]
    if len(bs) > 1:
        jiao = bs[1]
    r_yuan = [i for i in reversed(yuan)]
    count = 0
    for i in range(len(yuan)):
        if i == 0:
            r_yuan[i] += '圆'
            continue
        r_yuan[i] += chinese2[count]
        count += 1
        if count == 4:
            count = 0
            chinese2[3] = '亿'

    s_jiao = [i for i in jiao][:3]  # 去掉小于厘之后的

    j_count = -1
    for i in range(len(s_jiao)):
        s_jiao[i] += chinese2[j_count]
        j_count -= 1
    last = [i for i in reversed(r_yuan)] + s_jiao
    last_str = ''.join(last)
    for i in range(len(last_str)):
        digital = last_str[i]
        if digital in chinese:
            last_str = last_str.replace(digital, chinese[digital])

    # print(last_str)
    last_str = re.sub('零[仟佰拾]','零',last_str)
    last_str = re.sub('零+','零',last_str)
    # print(last_str)
    last_str = re.sub('([仟佰拾])零万',r'\1万',last_str)
    last_str = re.sub('零+圆','圆',last_str)
    return last_str
    
print(digital_to_chinese(960645))
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值