阿拉伯数字转大写汉字的python代码
时间: 2024-02-18 11:32:24 浏览: 105
以下是将阿拉伯数字转换为大写汉字的Python代码:
```
# coding=utf-8
chinese_num = {
'0': '零',
'1': '壹',
'2': '贰',
'3': '叁',
'4': '肆',
'5': '伍',
'6': '陆',
'7': '柒',
'8': '捌',
'9': '玖'
}
chinese_unit = {
0: '',
1: '拾',
2: '佰',
3: '仟',
4: '万',
5: '拾',
6: '佰',
7: '仟',
8: '亿',
9: '拾',
10: '佰',
11: '仟'
}
def num_to_chinese(num):
num_str = str(num)
length = len(num_str)
result = ''
for i in range(length):
digit = int(num_str[i])
unit = length - i - 1
if digit != 0:
result += chinese_num[str(digit)] + chinese_unit[unit]
else:
if unit == 4 or unit == 8:
result += chinese_unit[unit]
elif result[-1] != chinese_num['0']:
result += chinese_num['0']
if result[-1] == chinese_num['0'] and len(result) > 1:
result = result[:-1]
return result
if __name__ == '__main__':
num = 123456789
print(num_to_chinese(num)) # 一亿二千三百四十五万六千七百八十九
```
该代码将阿拉伯数字转换为大写汉字,并且考虑了0的位置以及亿、万的单位。
阅读全文