8 Jan 2004 afayolle   » (Master)

Someone on fr.comp.lang.python asked for a way to format a float as a french currency (i.e. with thousands separator). There doesn't seem to be anything available in the standard library and the % operator has no specific format for currency. Here's the code I came up with:

def as_currency(amount, thousand_sep=' ', decimal_sep=',', symbol='ยค'):
    num = '%.2f'%amount
    left, right = num.split('.')
    left_digits = list(left)
    spaced_digits = [decimal_sep, right, symbol ]
    while left_digits:
        spaced_digits = [thousand_sep] + left_digits[-3:] + spaced_digits
        del left_digits[-3:]
    return ''.join(spaced_digits[1:])

This could probably be enhanced by using the locale module to get the values. It's rather unfortunate that locale.format has not % substitution for currencies.

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!