Currency formatting

May 17, 2017 1 minute
      def currency(value, group_sep=' ', decimal_sep='.'):
         """Format currency by digits.
      
         >>> currency(100)
         '100.00'
         >>> currency(3.1415)
         '3.14'
         >>> currency(31415)
         '31 415.00'
         >>> currency(3141500.1)
         '3 141 500.10'
         >>> currency(31415000.1)
         '31 415 000.10'
         """
         head,tail = ('%.2f'%value).split('.')
         l = len(head)
         return group_sep.join([head[r-3:l+r] for r in xrange(0,-l,-3)][::-1]) + decimal_sep + tail
      

      Gist


      Have a comment on one of my posts? Start a discussion in my public inbox by sending an email to ~histrio/[email protected] [mailing list etiquette]