用python把阿拉伯数字转成大写汉字数字(精确到分)写自定义目录标题
用python把阿拉伯数字转成大写汉字数字(精确到分)
功能
阿拉伯数字 | 大写数字 |
---|---|
5200 | 伍仟贰佰圆整 |
3200.19 | 叁仟贰佰圆壹角玖分 |
10235.32 | 壹万零贰佰叁拾伍圆叁角贰分 |
# 函数主体
chinese_dict = {
0: "零",
1: "壹",
2: "贰",
3: "叁",
4: "肆",
5: "伍",
6: "陆",
7: "柒",
8: "捌",
9: "玖",
}
unit_list = ["", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "兆"]
def transform(number):
number = number.strip()
try:
number = float(number)
except:
return None
integer_part = int(number)
decimal_part = round(number - integer_part, 2)
# Convert integer part
if integer_part == 0:
chinese_integer = "零"
else:
chinese_integer = ""
integer_str = str(integer_part)
zero_flag = False # Flag to handle consecutive zeros
for i, digit in enumerate(integer_str):
digit = int(digit)
if digit != 0:
if zero_flag:
chinese_integer += "零"
zero_flag = False
chinese_integer += (
chinese_dict[digit] + unit_list[len(integer_str) - i - 1]
)
else:
zero_flag = True
# Convert decimal part
if decimal_part == 0:
chinese_decimal = "整"
# 如果不想要加入“整”,只需要把此处改成 chinese_decimal = ""
else:
chinese_decimal = ""
decimal_str = str(decimal_part).split(".")[
1
] # Get the decimal part as a string
for i, digit in enumerate(decimal_str):
digit = int(digit)
chinese_decimal += chinese_dict[digit] + ("角" if i == 0 else "分")
# Combine integer and decimal parts
chinese_number = chinese_integer + "圆" + chinese_decimal
# 如果把大写数字复制到剪贴板,去掉下面的#和空格
# pyperclip.copy(chinese_number)
print(chinese_number)
return chinese_number
运行结果
def generate_random_number():
import random
number = random.uniform(100, 1000000000) # 生成1到100000之间的随机浮点数
rounded_number = round(number, 2) # 保留两位小数
print(rounded_number)
return rounded_number
if __name__ == "__main__":
# number_str = pyperclip.paste()
# transform(number_str)
# # 测试函数
# print(transform("3200.19")) # 叁仟贰佰圆壹角玖分
# print(transform("5200")) # 伍仟贰佰圆整
# print(transform("10235.19")) # 伍仟贰佰圆整
for i in range(10):
number = generate_random_number()
number_str = str(number)
transform(number_str)
807140193.03
# 捌亿零柒佰壹拾肆万零壹佰玖拾叁圆零角叁分
228639920.86
# 贰亿贰仟捌佰陆拾叁万玖仟玖佰贰拾圆捌角陆分
312602274.81
# 叁亿壹仟贰佰陆拾零贰仟贰佰柒拾肆圆捌角壹分
560913259.47
# 伍亿陆仟零玖拾壹万叁仟贰佰伍拾玖圆肆角柒分
138063665.55
# 壹亿叁仟捌佰零陆万叁仟陆佰陆拾伍圆伍角伍分
639573365.46
# 陆亿叁仟玖佰伍拾柒万叁仟叁佰陆拾伍圆肆角陆分
55552320.23
# 伍仟伍佰伍拾伍万贰仟叁佰贰拾圆贰角叁分
113085265.24
# 壹亿壹仟叁佰零捌万伍仟贰佰陆拾伍圆贰角肆分
784031007.7
# 柒亿捌仟肆佰零叁万壹仟零柒圆柒角
263429203.87
# 贰亿陆仟叁佰肆拾贰万玖仟贰佰零叁圆捌角柒分