數字轉人名幣讀法(python)
阿新 • • 發佈:2021-01-26
實現將一個浮點型小數(整數部分不超過12位),保留兩位小數,轉化為大寫人名幣形式。考慮兩個及以上零連到一起的情況。
舉例:
程式碼:
def divide(num):
integer = int(num)
fraction = int(round((num-integer), 2)*100)
return (str(integer), str(fraction))
han_list = ["零", "壹", "貳", "叄", "肆" , "伍", "陸", "柒", "捌", "玖"]
unit_list = ["十", "百", "千"]
fra_list = ["角", "分"]
def four_to_hanstr(num_str):
result = ""
num_len = len(num_str)
for i in range(num_len):
num = int(num_str[i])
if i != num_len-1 and num != 0:
result += han_list[num] + unit_list[num_len-2-i]
else:
result += han_list[num]
return result
def integer_to_str(num_str):
str_len = len(num_str)
if str_len > 12:
print("數字太大,翻譯不了" )
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) + "元"
def shanchu(han_str):
shan_list = []
for i in range(len(han_str)):
if han_str[i] == '零':
for j in range(i+1, len(han_str)):
if han_str[j] == "零":
shan_list.append(j)
else:
break
hanlist = list(han_str)
for i in shan_list:
del hanlist[i]
han_str = ""
for i in range(len(hanlist)):
han_str += hanlist[i]
return han_str
def fraction_to_str(num_str):
result = ""
if len(num_str) == 1:
num0 = 0
num1 = int(num_str[0])
else:
num0 = int(num_str[0])
num1 = int(num_str[1])
if num0 != 0:
result += han_list[num0] + fra_list[0]
if num1 != 0:
result += han_list[num1] + fra_list[1]
elif num1 != 0 :
result += han_list[num0]
result += han_list[num1] + fra_list[1]
else:
result = "整"
return result
num = float(input("請輸入一個浮點數:"))
integer, fraction = divide(num)
print(shanchu(integer_to_str(integer))+fraction_to_str(fraction))