Python阿拉伯数字转换为汉字,小数点用汉字点代替P
时间: 2024-05-15 07:14:53 浏览: 11
以下是Python代码实现:
```python
# coding=utf-8
def num2cn(num):
"""
将阿拉伯数字转换为汉字,小数点用汉字点代替
:param num: 阿拉伯数字
:return: 汉字
"""
nums = {
0: '零',
1: '一',
2: '二',
3: '三',
4: '四',
5: '五',
6: '六',
7: '七',
8: '八',
9: '九',
10: '十'
}
if num == 0:
return nums[0]
if isinstance(num, float):
num_str = str(num)
integer, decimal = num_str.split('.')
integer_cn = num2cn(int(integer))
decimal_cn = ''.join([nums[int(digit)] for digit in decimal])
return integer_cn + '点' + decimal_cn
if num < 0:
return '负' + num2cn(-num)
if num < 10:
return nums[num]
if num < 20:
return nums[10] + nums[num - 10]
if num < 100:
decade = num // 10
unit = num % 10
if unit == 0:
return nums[decade] + nums[10]
else:
return nums[decade] + nums[10] + nums[unit]
if num < 1000:
hundred = num // 100
rest = num % 100
if rest == 0:
return nums[hundred] + '百'
else:
return nums[hundred] + '百' + num2cn(rest)
if num < 10000:
thousand = num // 1000
rest = num % 1000
if rest == 0:
return nums[thousand] + '千'
else:
return nums[thousand] + '千' + num2cn(rest)
if num < 100000000:
ten_thousand = num // 10000
rest = num % 10000
if rest == 0:
return num2cn(ten_thousand) + '万'
else:
return num2cn(ten_thousand) + '万' + num2cn(rest)
billion = num // 100000000
rest = num % 100000000
if rest == 0:
return num2cn(billion) + '亿'
else:
return num2cn(billion) + '亿' + num2cn(rest)
```
使用示例:
```python
print(num2cn(123456789)) # 一亿二千三百四十五万六千七百八十九
print(num2cn(0)) # 零
print(num2cn(-123.45)) # 负一百二十三点四五
```
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)