monetary applications (et al)

Dan Bishop danb_83 at yahoo.com
Thu Sep 19 15:45:47 EDT 2002


terry <tg5027 at citlink.net> wrote in message news:<mailman.1032383305.18515.python-list at python.org>...
> ...
> I do admit to being OO inhibited, so maybe you could take it from this 
> short piece code and execution results, and, provide a brief 
> description of what you would put into this money class that would 
> eliminate this error message, while maintaining the code simplicity.
> [code snipped]
> ...

def _roundToEven(x):
   if x < 0:
      return -_round(-x)
   iPart, fPart = divmod(x, 1.)
   iPart = int(iPart)
   if fPart == 0.5:
      if iPart & 1:
         return iPart + 1
      else:                
         return iPart      
   elif fPart > 0.5:
      return iPart + 1
   else:
      return iPart


class Money(object):
   def __init__(self, dollars):
      self.__cents = _roundToEven(dollars * 100)
   def __repr__(self):
      return "Money(%0.2f)" % float(self)
   def __str__(self):
      return "$%0.2f" % float(self)
   def __float__(self):
      return self.__cents / 100.
   def __pos__(self):
      return self
   def __neg__(self):
      return Money(-float(self))
   def __add__(self, other):
      assert isinstance(other, Money)
      return Money(float(self) + float(other))
   def __sub__(self, other):
      assert isinstance(other, Money)
      return Money(float(self) - float(other))
   def __mul__(self, other):
      return Money(float(self) * other)
   def __div__(self, other):
      if isinstance(other, Money):
         return float(self) / float(other)
      else:
         return Money(float(self) / other)
   def __cmp__(self, other):
      return (self.__cents).__cmp__(other.__cents)
   def __hash__(self):
      return hash(float(self))



More information about the Python-list mailing list