Jinja Templates - Format a float as comma-separated currency

后端 未结 6 1714
轻奢々
轻奢々 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:47

    Custom Filter using Babel (Can be used to format other currencies as well)

    Install Babel (http://babel.pocoo.org/en/latest/api/numbers.html)

    pip install Babel
    

    Custom Jinja Filter

    from babel.numbers import format_currency
    
    @app.template_filter()
    def usdollar(value):
       return format_currency(value, 'USD', locale='en_US')
    
    app.jinja_env.filters['usdollar'] = usdollar
    

    Usage in Jinja Template:

    {{ '-10000.500' | usdollar }}
    
    Output : -$10,000.50
    

提交回复
热议问题