Don't like ads? PRO users don't see any ads ;-)

Money/number format - Python

By: vellonce on Jul 20th, 2012  |  syntax: Python  |  size: 1.69 KB  |  hits: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import Decimal
  2.  
  3. def moneyfmt(value, places=2, curr='', sep=',', dp='.',
  4.              pos='', neg='-', trailneg=''):
  5.     """Convert Decimal to a money formatted string.
  6.  
  7.    places:  required number of places after the decimal point
  8.    curr:    optional currency symbol before the sign (may be blank)
  9.    sep:     optional grouping separator (comma, period, space, or blank)
  10.    dp:      decimal point indicator (comma or period)
  11.             only specify as blank when places is zero
  12.    pos:     optional sign for positive numbers: '+', space or blank
  13.    neg:     optional sign for negative numbers: '-', '(', space or blank
  14.    trailneg:optional trailing minus indicator:  '-', ')', space or blank
  15.  
  16.    >>> d = Decimal('-1234567.8901')
  17.    >>> moneyfmt(d, curr='$')
  18.    '-$1,234,567.89'
  19.    >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
  20.    '1.234.568-'
  21.    >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
  22.    '($1,234,567.89)'
  23.    >>> moneyfmt(Decimal(123456789), sep=' ')
  24.    '123 456 789.00'
  25.    >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
  26.    '<0.02>'
  27.  
  28.    """
  29.     q = Decimal(10) ** -places      # 2 places --> '0.01'
  30.     sign, digits, exp = value.quantize(q).as_tuple()
  31.     result = []
  32.     digits = map(str, digits)
  33.     build, next = result.append, digits.pop
  34.     if sign:
  35.         build(trailneg)
  36.     for i in range(places):
  37.         build(next() if digits else '0')
  38.     build(dp)
  39.     if not digits:
  40.         build('0')
  41.     i = 0
  42.     while digits:
  43.         build(next())
  44.         i += 1
  45.         if i == 3 and digits:
  46.             i = 0
  47.             build(sep)
  48.     build(curr)
  49.     build(neg if sign else pos)
  50.     return ''.join(reversed(result))