python convert number to Chinese

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def num2chinese(num: float or int):
    mapping = {
        '1': '壹',
        '2': '贰',
        '3': '叁',
        '4': '肆',
        '5': '伍',
        '6': '陆',
        '7': '柒',
        '8': '捌',
        '9': '玖',
        '0': '零',
    }
    if num == 0:
        return mapping['0'] + '元整'
    base_unit = {
        0: '',
        1: '拾',
        2: '佰',
        3: '仟',
    }
    unit_integers = {
        -1: '',
        0: '万',
        1: '億',
        2: '兆'
    }
    unit_fractions = {
        '0': '',
        '1': '角',
        '2': '分'
    }
    max_unit = max(list(unit_integers.keys())) + 1
    result = ''
    # num = str(float(num)).split('.')
    num = str(num).split('.')
    if len(num) == 1 or not int(num[1]):
        result += unit_fractions['0']
    else:
        tmp_fraction = num[1]
        try:
            if int(tmp_fraction[1]):
                result += unit_fractions['2']
                result += mapping[tmp_fraction[1]]
        except IndexError:
            pass
        if int(tmp_fraction[0]):
            result += unit_fractions['1']
            result += mapping[tmp_fraction[0]]
    if not result:
        result += '整'
    result += '元'
    integers = num[0][::-1]
    unit_count = 0
    tmp_unit = ''
    while True:
        tmp = integers[0:4]
        if len(tmp) == 0:
            break
        if int(tmp) == 0:
            if unit_count == max_unit:
                unit_count = 0
                result += unit_integers[max_unit - 1]
            tmp_unit = unit_integers[unit_count]
            unit_count += 1
        else:
            result += tmp_unit
            break
        integers = integers[4:]
    base_unit_count = -1
    for i in range(0, len(integers), 4):
        v = integers[i: i + 4]
        continual_zero = True
        tmp = ''
        is_zero = True
        for x in range(len(v)):
            if v[x] == '0' and continual_zero:
                pass
            elif v[x] == '0' and not continual_zero:
                tmp += mapping[v[x]]
                continual_zero = True
            else:
                is_zero = False
                continual_zero = False
                tmp += base_unit[x]
                tmp += mapping[v[x]]
        if is_zero:
            pass
        else:
            result += (unit_integers[base_unit_count] + tmp)
        base_unit_count += 1
        base_unit_count %= max_unit
    if result[-1] == '元':
        return result[2::-1]
    return result[::-1]
Licensed under CC BY-NC-SA 4.0