類練習題1:將浮點數轉化為金額的類
阿新 • • 發佈:2019-02-02
該程式可當做模組匯入使用,也可直接執行,直接執行結果如下:#!/usr/bin/env python class MoneyFmt(object): def __init__(self, money, mark=False): self.__money = money self.__mark = mark def __str__(self): return str(self.__dollarize()) def __repr__(self): return '%s' % self.__money def __nonzero__(self): return bool(self.__money) def update(self, new_money): self.__money = new_money def __dollarize(self): if "-" not in str(self.__money): li = list(str(self.__money).split('.')[0]) else: li = list(str(self.__money).split('.')[0])[1:] if len(li) <= 3: if "-" not in str(self.__money): return "$%.2f" % self.__money else: if self.__mark == False: return "-$%.2f" % abs(self.__money) elif self.__mark == True: return "<->$%.2f" % abs(self.__money) else: rev = "%.2f" % self.__money if "-" not in rev: li = list(rev.split('.')[0]) else: li = list(rev.split('.')[0])[1:] length = len(li) x = divmod(length, 3) if x[1] != 0: count = x[0] else: count = x[0]-1 i = 1 while i <= count: li.insert((length-3), ',') i += 1 length -= 3 if "-" not in rev: string = "$" + ''.join(li) + rev[-3:] else: if self.__mark == False: string = "-$" + ''.join(li) + rev[-3:] elif self.__mark == True: string = "<->$" + ''.join(li) + rev[-3:] return string def _test(): x = MoneyFmt(123456.789) y = MoneyFmt(0.5) z = MoneyFmt(-123) m = MoneyFmt(-123.456,mark=True) print x print y print z print m if __name__ == "__main__": _test()