python實現人民幣大寫轉換


問題描述:

銀行在打印票據的時候,常常需要將阿拉伯數字表示的人民幣金額轉換為大寫表示,現在請你來完成這樣一個程序。

在中文大寫方式中,0到10以及100、1000、10000被依次表示為: 零 壹 貳 叄 肆 伍 陸 柒 捌 玖 拾 佰 仟 萬

以下的例子示范了阿拉伯數字到人民幣大寫的轉換規則:

1 壹圓

11 壹拾壹圓

111 壹佰壹拾壹圓

101 壹佰零壹圓

-1000 負壹仟圓

1234567 壹佰貳拾叄萬肆仟伍佰陸拾柒圓

現在給你一個整數a(|a|<100000000), 請你打印出人民幣大寫表示.

例如:a=1

則輸出:壹圓

注意:請以Unicode的形式輸出答案。提示:所有的中文字符,在代碼中直接使用其Unicode的形式即可滿足要求,中文的Unicode編碼可以通過如下方式獲得:u'壹'。

這題目最頭疼的地方是當一串數字中間和末尾都存在0的時候,要去掉重復出現的0和對應的單位。

例如:             6100 0310元

對應的大寫為:   陸仟壹佰萬零叄佰壹拾圓

這里6100后面的零轉換成大寫之后都去掉了,0310個位數上的0也去掉了,但是千位上的數字0保留。

 1 num_dic = {'0':u'', '1':u'', '2':u'', '3':u'', '4':u'', '5':u'', '6':u'', '7':u'', '8':u'', '9':u''}
 2 unit_dic = {0:u'', 1:'', 2:'', 3:'', 4:'', 5:'', 6:'', 7:''}
 3 decimal_dic={0:u'',1:u'',2:u'',3:u''}
 4 def convert_int(num):
 5     temp = []
 6     t = str('%8d'%abs(num))    #重點:把數字換成固定長度8位的字符串
 7     for s in range(0,4):
 8         if t[s] != ' ' and t[s] != '0':
 9             temp.append(num_dic[t[s]])
10             temp.append(unit_dic[s])
11         if t[s] == '0' and s <3 and t[s+1] != '0':
12             temp.append(num_dic[t[s]])
13     if(t[2] != ' ' and t[3] == '0'):
14         temp.append('')
15     for s in range(4,8):
16         if t[s] != ' ' and t[s] != '0':
17             temp.append(num_dic[t[s]])
18             temp.append(unit_dic[s])
19         if t[s] == '0' and s < 7 and t[s+1] != '0':
20             temp.append(num_dic[t[s]])
21     temp = ''.join(temp)
22     if num < 0:
23         temp = '' + temp
24     if num == 0:
25         temp = '' + temp
26 
27     return temp + u''
28 
29 def convert_decimal(num):
30     t = str('%4d'%num)
31     temp = []
32     for s in range(0,4):
33         if t[s] != ' ' and t[s] != '0':
34             temp.append(num_dic[t[s]])
35             temp.append(decimal_dic[s])
36         if t[s] == '0' and s < 3 and t[s + 1] != '0':
37             temp.append(num_dic[t[s]])
38     temp = ''.join(temp)
39     if len(temp) == 0:
40         return ''
41     return temp
42 
43 def convert_money(money):
44     num = round(float(money),4)
45     integer,decimal = str(num).split('.')
46     result_int = convert_int(int(integer))
47     result_decimal = convert_decimal(int(decimal))
48     return result_int+result_decimal
49 
50 money = input('請輸入轉換的金額:')
51 print(convert_money(money))
python實現人民幣大寫轉換


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM