小伙伴們應該收到過銀行賬單,賬單上的金額可能會寫成金額大寫的形式,比如“您本月的信用卡賬單陸萬叁仟元整”,那么肯定會需要一個方法將數字轉換成這種形式。
規則不難,但是用代碼實現的時候還是會有點小坑,不信的話可以先自己寫的試試。
壹貳叁肆伍陸柒捌玖拾佰仟萬億壹貳叁肆伍陸柒捌玖拾佰仟萬億壹貳叁肆伍陸柒捌玖拾佰仟萬億壹貳叁肆伍陸柒捌玖拾佰仟萬億壹貳叁肆伍陸柒捌玖拾佰仟萬億壹貳叁肆伍陸柒捌玖拾佰仟萬億壹貳叁肆伍陸柒捌玖拾佰仟萬億
下面的代碼是將 -999999999999 到 999999999999 的整數轉換成金額大寫形式,如果還要加上帶兩位小數的,大家在這個基礎上改一下就可以了。總共四十幾行,就不加注釋了
#encoding=utf-8 class Num2Chinese: def __init__(self): self.ch = ['零','壹','貳','叁','肆','伍','陸','柒','捌','玖'] self.unit0 = ['仟','佰','拾',''] self.unit1 = ['億','萬',''] # 不大于10000的數 def convertFor0000(self,num): tmp = ('0000' + str(num))[-4:] if tmp=='0000': return '零' else: tmpCh = '' for i in range(4): tmpCh += self.ch[int(tmp[i])] + self.unit0[i] tmpCh = tmpCh.replace("零仟","零").replace("零佰","零").replace("零拾","零") tmpCh = tmpCh.replace("零零零零","零").replace("零零零", "零").replace("零零", "零") if tmpCh.endswith('零'): tmpCh = tmpCh[0:-1] return tmpCh def convert(self,num): if num>0 and num <= 999999999999: tmp = ('000000000000' + str(num))[-12:] tmpCh = '' for i in range(0, 12, 4): numStr = tmp[i:i + 4] tmpCh += self.convertFor0000(numStr) + self.unit1[i // 4] tmpCh = tmpCh.replace("零億", "零").replace("零萬", "零") tmpCh = tmpCh.replace("零零零零", "零").replace("零零零", "零").replace("零零", "零") if tmpCh.startswith('零'): tmpCh = tmpCh[1:] if tmpCh.endswith('零'): tmpCh = tmpCh[0:-1] # if tmpCh.startswith('一十'): # tmpCh = tmpCh[1:] return tmpCh elif num<0 and num >= -999999999999: return '負' + self.convert(0-num) elif num == 0: return '零' elif num>999999999999 or num<-999999999999: return '超出范圍' else: return '未知' if __name__=='__main__': print(Num2Chinese().convert(100108500010))