han_list=["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"]
unit_list=["拾","佰","仟"]
#把整数部分和小数部分转化为字符串,并存入元组作为返回值
def devide(num):
integer=int(num)#整数部分
fraction=round((num-integer)*100)#小数部分
#若小数部分小于10要在前面加零
if fraction<10:
return(str(integer),"0"+str(fraction))
return (str(integer),str(fraction))
#每四位数字转化为人民币读法
def four_to_hanstr(num_str):
result=""#记录人民币读法
num_len=len(num_str)
for i in range(num_len):
num=int(num_str[i])
#若有两个0连用,只读一个0;
if i!=num_len-1 and num_str[i]=="0" and num_str[i+1]=="0":
pass
else:
if i !=num_len-1 and num !=0:
result+=han_list[num]+unit_list[num_len-2-i]
else:
#最后一位是0不需要读
if num_str[-1]=="0":
return result
result+=han_list[num]
return result
#小数部分转人民币读法
def frac_to_hanstr(num_str):
result=""
num_len=len(num_str)
for i in range(num_len):
num=int(num_str[i])
result+=han_list[num]
return result
#整数部分转人民币读法
def integer_to_str(num_str):
str_len=len(num_str)
if str_len>12:
print("数字太大,翻译不了")
return
elif str_len>8:
return four_to_hanstr(num_str[:-8])+"亿"+four_to_hanstr(num_str[-8:-4])+"万"
+four_to_hanstr(num_str[-4:])
elif str_len>4:
return four_to_hanstr(num_str[:-4])+"万"+four_to_hanstr(num_str[-4:])
else:
return four_to_hanstr(num_str)
#程序数据测试
num=float(input("请输入一个浮点数>>>"))
integer,fraction=devide(num)
integer_to_han_str=integer_to_str(integer)
fraction_to_han_str=frac_to_hanstr(fraction)
han_str=integer_to_han_str+"点"+fraction_to_han_str+"元"
print(han_str)