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

FOAF updates: Trust rankings are now exported, making the data available to other users and websites. An external FOAF URI has been added, allowing users to link to an additional FOAF file.

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!