数字汉字转换python
时间: 2023-11-04 17:02:43 浏览: 102
以下是一个将数字转换为汉字的Python程序:
```python
# -*- coding: utf-8 -*-
def num_to_chinese(num):
chinese_num = {0: '零', 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '七', 8: '八', 9: '九'}
chinese_unit = ['', '十', '百', '千', '万', '亿']
result = ''
if num == 0:
return chinese_num[0]
if num < 0:
result += '负'
num = abs(num)
i = 0
while num > 0:
digit = num % 10
if digit != 0 or (digit == 0 and i % 4 == 0):
result = chinese_num[digit] + chinese_unit[i % 5] + result
i += 1
num //= 10
result = result.replace('零零', '零')
result = result.replace('零万', '万')
result = result.replace('零亿', '亿')
result = result.replace('亿万', '亿')
if result[-1] == '零':
result = result[:-1]
return result
if __name__ == '__main__':
num = 123456789
print(num_to_chinese(num))
```
输出结果为:一亿二千三百四十五万六千七百八十九。
阅读全文