Money data type

Phil Schmidt phil_nospam_schmidt at yahoo.com
Thu Sep 18 19:10:00 CEST 2003

```Try this:
-------------------------
import types

class USD:
"""
This class represents money in US Dollars, does math on it,
prints it, etc. All dollar amounts are stored in cents, and no
fractional cents are allowed. Rounding is supported for fractional
cent values that are passed in.
"""
def __init__(self, value=0):
"""U.S. Dollars, stored in cents."""
if isinstance(value, USD):
self.value = value.value
else:
self.value = int(round(value * 100))

def __repr__(self):
"""This is returns a string that may be exec'ed to get a duplicate."""
s = '%03i' % self.value
s = 'USD(%s.%s)' % (s[:-2], s[-2:])
return s

def __str__(self):
"""return a nice formatted printable string"""
return '\$%9.2f' % (float(self.value) / 100)

def STR(self):
"""return a 'raw' formatted printable string"""
return '%0.2f' % (float(self.value) / 100)

"""perform self + value"""
# handle the case where value is a string
if type(value) is types.StringType:
return self.__str__() + value
# otherwise it's assumed to be a numeric type
m = USD(value)
m.value += self.value
return m

"""perform value + self"""
# handle the case where value is a string
if type(value) is types.StringType:
return value + self.__str__()
# otherwise it's assumed to be a numeric type
m = USD(value)
m.value += self.value
return m

def __sub__(self, value):
"""returns a USD instance containing the difference between self and value"""
m = USD(value)
m.value = self.value - m.value
return m

def __rsub__(self, value):
"""returns a USD instance containing the difference between value and self"""
m = USD(value)
m.value -= self.value
return m

"""perform self += value"""
m = USD(value)
self.value += m.value
return self

def __isub__(self, value):
"""perform self -= value"""
m = USD(value)
self.value -= m.value
return self

def __neg__(self):
"""return negated self"""
m = USD()
m.value = -self.value
return m

def __pos__(self):
"""return self"""
m = USD()
m.value = self.value
return m

def __lt__(self, value):
"""perform self < value"""
m = USD(value)
return self.value < m.value
def __gt__(self, value):
"""perform self > value"""
m = USD(value)
return self.value > m.value

def __eq__(self, value):
"""perform self == value"""
m = USD(value)
return self.value == m.value

def __ne__(self, value):
"""perform self != value"""
m = USD(value)
return self.value != m.value

def __le__(self, value):
"""perform self < value"""
m = USD(value)
return self.value <= m.value

def __ge__(self, value):
"""perform self < value"""
m = USD(value)
return self.value >= m.value

```