I\'m trying to format a float as comma-separated currency. E.g. 543921.9354
becomes $543,921.94
. I\'m using the format
filter in Jinja t
To extend @alex vasi's answer, I would definitely write a custom filter, but I'd also use python's own locale
functionality, which handles currency grouping, and the symbol,
def format_currency(value):
return locale.currency(value, symbol=True, grouping=True)
The main thing to take note of using locale
is that it doesn't work with the default 'C' locale, so you have to set it so something that's available on your machine.
For what you're looking for, you probably need,
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
but if you wanted sterling pounds, you'd use,
locale.setlocale(locale.LC_ALL, 'en_GB.UTF_8')
.
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
locale.currency(543921.94, symbol=True, grouping=True)
> '$543,921.94'
locale.setlocale(locale.LC_ALL, 'en_GB')
> '£543,921.94'