阿拉伯數字金額轉中文大寫 (python實現)

分析

  • 分小數和整數部分進行處理
  • 末尾的零應捨棄
  • 中間有連續多個零,只取一個零
  • 整數部分從右往左以4位爲步長掃描

實現

# -*- coding: utf-8 -*-
from __future__ import unicode_literals


def convert(n):
    units = ['', '萬', '億']
    nums = ['零', '壹', '貳', '叄', '肆', '伍', '陸', '柒', '捌', '玖']
    decimal_label = ['角', '分']
    small_int_label = ['', '拾', '佰', '仟']
    int_part, decimal_part = str(int(n)), str(n - int(n))[2:]  # 分離整數和小數部分

    res = []
    if decimal_part:
        res.append(''.join([nums[int(x)] + y for x, y in zip(decimal_part, decimal_label) if x != '0']))

    if int_part != '0':
        res.append('圓')
        while int_part:
            small_int_part, int_part = int_part[-4:], int_part[:-4]
            tmp = ''.join([nums[int(x)] + (y if x != '0' else '') for x, y in zip(small_int_part[::-1], small_int_label)[::-1]])
            tmp = tmp.rstrip('零').replace('零零零', '零').replace('零零', '零')
            unit = units.pop(0)
            if tmp:
                tmp += unit
                res.append(tmp)
    return ''.join(res[::-1])


print convert(0.22)
print convert(0.20)
print convert(0.02)

print convert(1)
print convert(12)
print convert(123)
print convert(1234)
print convert(1230)
print convert(1204)
print convert(1034)
print convert(1004)

print convert(51234)
print convert(51204)
print convert(51034)
print convert(50234)
print convert(50034)
print convert(50004)
print convert(50000)

print convert(12351234)
print convert(12301234)
print convert(12351234)
print convert(12051234)
print convert(10351234)
print convert(10051234)
print convert(10001234)
print convert(10000000)
print convert(10000004)
print convert(10000030)
print convert(10000200)
print convert(10001000)
print convert(10050000)

print convert(12000010001)
print convert(1409.50)

輸出:
貳角貳分
貳角
貳分
壹圓
壹拾貳圓
壹佰貳拾叄圓
壹仟貳佰叄拾肆圓
壹仟貳佰叄拾圓
壹仟貳佰零肆圓
壹仟零叄拾肆圓
壹仟零肆圓
伍萬壹仟貳佰叄拾肆圓
伍萬壹仟貳佰零肆圓
伍萬壹仟零叄拾肆圓
伍萬零貳佰叄拾肆圓
伍萬零叄拾肆圓
伍萬零肆圓
伍萬圓
壹仟貳佰叄拾伍萬壹仟貳佰叄拾肆圓
壹仟貳佰叄拾萬壹仟貳佰叄拾肆圓
壹仟貳佰叄拾伍萬壹仟貳佰叄拾肆圓
壹仟貳佰零伍萬壹仟貳佰叄拾肆圓
壹仟零叄拾伍萬壹仟貳佰叄拾肆圓
壹仟零伍萬壹仟貳佰叄拾肆圓
壹仟萬壹仟貳佰叄拾肆圓
壹仟萬圓
壹仟萬零肆圓
壹仟萬零叄拾圓
壹仟萬零貳佰圓
壹仟萬壹仟圓
壹仟零伍萬圓
壹佰貳拾億零壹萬零壹圓
壹仟肆佰零玖圓伍角

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章