实现代码一
代码较为简洁,原文链接: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))