借助如下两个列表,将输入的人民币数值转换成大写
时间: 2023-05-25 10:05:46 浏览: 148
人民币小写金额转大写
数值:
```
num_list = [
'', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'
]
unit_list = [
'', '拾', '佰', '仟', '万'
]
```
代码如下:
```python
def rmb_to_upper(num):
"""
将人民币数值转换成大写
:param num: 人民币数值,float类型,精确到分
:return: 大写人民币字符串
"""
# 数字部分的转换
integer_part = int(num)
decimal_part = int(round((num - integer_part) * 100))
integer_str = str(integer_part)
decimal_str = str(decimal_part)
integer_length = len(integer_str)
integer_list = [int(i) for i in integer_str] # 将整数部分转换成列表
result = ''
index = 0
# 处理整数部分
for i in range(integer_length - 1, -1, -1): # 从个位往前处理
num = integer_list[i]
if num == 0:
if i % 4 == 0 and result[-1:] != '万':
result += unit_list[i]
else:
result = num_list[num] + unit_list[i] + result
index = i
# 添加万
if index >= 4 and result[-1:] != '万':
result += '万'
# 处理小数部分
decimal_length = len(decimal_str)
if decimal_length == 1:
decimal_str += '0'
decimal_num = int(decimal_str)
if decimal_num == 0:
result += '整'
else:
d0 = decimal_num // 10
d1 = decimal_num % 10
if d0 == 0:
result += num_list[d1] + '分'
else:
result += num_list[d0] + '角' + num_list[d1] + '分'
return result
```
测试样例:
```python
print(rmb_to_upper(100000001.01)) # 壹亿零壹元零壹分
print(rmb_to_upper(0)) # 零元整
print(rmb_to_upper(0.01)) # 零元壹分
print(rmb_to_upper(0.1)) # 零元壹角
print(rmb_to_upper(0.11)) # 零元壹角壹分
print(rmb_to_upper(1000000)) # 壹佰万元整
print(rmb_to_upper(1001000)) # 壹佰万元壹仟元整
print(rmb_to_upper(1030000)) # 壹佰零叁万元整
print(rmb_to_upper(10001000)) # 壹仟万元壹仟元整
print(rmb_to_upper(100000005)) # 壹亿零伍元整
print(rmb_to_upper(123456789.98)) # 壹亿贰仟叁佰肆拾伍万陆仟柒佰捌十玖元玖角捌分
print(rmb_to_upper(5322892.88)) # 伍佰叁拾贰万贰仟捌佰玖拾贰元捌角捌分
```
阅读全文