Jinja Templates - Format a float as comma-separated currency

后端 未结 6 1722
轻奢々
轻奢々 2021-01-30 16:21

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

6条回答
  •  旧巷少年郎
    2021-01-30 16:57

    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'
    

提交回复
热议问题