最近工作需要旁舰,得把金額轉換成大寫格式锋华,google了一遍,沒發(fā)現(xiàn)特別滿意的輪子箭窜,耗費近一通宵毯焕,自己造了一個。python3.6+的,金額超過一億的就先不管了纳猫,業(yè)務上不需要婆咸。代碼于2019年2月份部署到生產(chǎn)環(huán)境上,至今運行良好芜辕。
#!/usr/bin/env python3
import re
from decimal import Decimal, ROUND_HALF_UP
ZH_HANS_MAP = dict(zip(range(10), "零壹貳叁肆伍陸柒捌玖"))
def verbose_price(cost):
"""convert price to zh_hans
>>> from decimal import Decimal
>>> verbose_price(Decimal(123456.34))
'壹拾貳萬叁仟肆佰伍拾陸元叁角肆分'
>>> verbose_price(123456.04)
'壹拾貳萬叁仟肆佰伍拾陸元零肆分'
>>> verbose_price(Decimal(123456.40))
'壹拾貳萬叁仟肆佰伍拾陸元肆角'
>>> verbose_price(123456.4)
'壹拾貳萬叁仟肆佰伍拾陸元肆角'
>>> verbose_price(123406.4)
'壹拾貳萬叁仟肆佰零陸元肆角'
>>> verbose_price(123006.4)
'壹拾貳萬叁仟零陸元肆角'
>>> verbose_price(100000)
'壹拾萬元整'
>>> verbose_price(110000)
'壹拾壹萬元整'
>>> verbose_price(110001)
'壹拾壹萬零壹元整'
>>> verbose_price(1010001)
'壹佰零壹萬零壹元整'
>>> verbose_price(2464.27)
'貳仟肆佰陸拾肆元貳角柒分'
"""
cost = Decimal(cost).quantize(Decimal('0.00'), ROUND_HALF_UP) # 四舍五入保留兩位小數(shù)
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("零")
if __name__ == "__main__":
import doctest
rs = doctest.testmod()
if rs.failed == 0:
print("All tests passed ~\nDone.")