python:数字转人民币大写

小写数字转人民币大写。简单的小程序,也比较实用。留住备用。

numtext = input('请输入金额:')
# 转换成2位小数
numtext = '{:.2f}'.format(eval(numtext))
numdx = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
danwei = ['分', '角', '元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿']
temptext = ''
tempid = 0
for i in numtext[::-1]:
    if i != '.':
        temptext = numdx[int(i)] + danwei[tempid] + temptext
        tempid += 1
print(temptext)

请输入金额:4536
肆仟伍佰叁拾陆元零角零分

更改一下,更接近阅读形式。

numtext = input('请输入金额:')
# 转换成2位小数
numtext = '{:.2f}'.format(eval(numtext))
numdx = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
danwei = ['分', '角', '元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿']
temptext = '零'
tempid = 0
for i in numtext[::-1]:
    if i != '.':
        if int(i) == 0:
            if danwei[tempid] in ['元','万']:
                temptext = danwei[tempid] + temptext
            elif temptext[0] not in ['零','元','万']:
                temptext = '零' + temptext
        else:
            temptext = numdx[int(i)] + danwei[tempid] + temptext
        tempid += 1
temptext = temptext[:-1]
if '亿万' in temptext:
    temptext = temptext.replace('亿万','亿')
    
print(temptext)

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个将人民币数值换成大写Python代码示例: ```python # 定义数字对应的大写汉字 digit_hanzi = { 0: '零', 1: '壹', 2: '贰', 3: '叁', 4: '肆', 5: '伍', 6: '陆', 7: '柒', 8: '捌', 9: '玖' } # 定义单位对应的大写汉字 unit_hanzi = { 0: '', 1: '拾', 2: '佰', 3: '仟', 4: '万', 5: '拾万', 6: '佰万', 7: '仟万', 8: '亿', 9: '拾亿', 10: '佰亿', 11: '仟亿' } def number_to_hanzi(num): # 将数字化为字符串,并翻 num_str = str(num)[::-1] hanzi_list = [] # 遍历数字字符串,获取对应的汉字 for i in range(len(num_str)): digit = int(num_str[i]) # 如果当前数字为零,且前一个数字不为零,则添加一个“零” if digit == 0 and (i == 0 or int(num_str[i-1]) != 0): hanzi_list.append(digit_hanzi[digit]) # 如果当前数字不为零,则添加对应的汉字和单位 elif digit != 0: hanzi_list.append(digit_hanzi[digit]) hanzi_list.append(unit_hanzi[i]) # 将汉字列表翻,并拼接成字符串 hanzi_list.reverse() hanzi_str = ''.join(hanzi_list) # 如果最后一个字符是“零”,则去掉 if hanzi_str.endswith('零'): hanzi_str = hanzi_str[:-1] return hanzi_str def rmb_to_hanzi(rmb): # 将人民币数值分为整数部分和小数部分 jiao, fen = divmod(int(round(rmb * 100)), 10) yuan, jiao = divmod(jiao, 10 ** 4) # 将整数部分和小数部分换成汉字 yuan_str = number_to_hanzi(yuan) + unit_hanzi[len(str(yuan))] jiao_str = number_to_hanzi(jiao) + unit_hanzi[1] fen_str = number_to_hanzi(fen) + unit_hanzi[0] # 根据小数部分是否为零,决定是否添加“整” if fen == 0: return yuan_str + '元整' else: return yuan_str + '元' + jiao_str + fen_str + '分' # 测试 print(rmb_to_hanzi(1024.56)) # 壹仟零贰拾肆元伍角陆分 print(rmb_to_hanzi(10000.00)) # 壹万元整 print(rmb_to_hanzi(123456789.12)) # 壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖元壹角贰分 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值