Search code examples
jinja2

How to format float with locale in Jinja2


I have format floats like 1234567.89 in Jinja2 to the german format with separators 1.234.567,89

{{ '{:,.2f}'.format(value) }} produces 1,234,567.89

How can I change the seperators?


Solution

  • To format the number you can use the locale module, but not sure if you can do it straight in the Jinja template, I made a filter instead - I am usually creating filters for re-usability.

    It's not clear how you are using Jinja; as standalone or as part of another application (Flask?). I am listing 2 methods/demos, 1 for standalone Jinja CLI, 1 for use in Flask.

    Jinja template, just pass the value to the filter.

    format_number_to_german.j2:

    {{ value | format_to_german }}
    

    For running jinja as CLI:

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    import sys
    from jinja2 import Environment, FileSystemLoader
    import locale
    
    ##################################################################################################
    def format_to_german(value):
        locale.setlocale(locale.LC_ALL, 'de_DE')
        return locale.format_string("%.2f", value, grouping=True)
    
    ##################################################################################################
    def main():
    
        file_loader = FileSystemLoader('templates')
        env = Environment(loader=file_loader)
        env.filters["format_to_german"] = format_to_german
    
        value = 12345673113.8912
    
        template = env.get_template('format_number_to_german.j2')
        output = template.render(value=value)
        print(output)
    
    # start:
    if __name__ == '__main__':
        main()
    

    Filter for Flask (in case you are using Jinja with Flask):

    @filters.app_template_filter('format_to_german')
    def format_to_german(value):
        import locale
        locale.setlocale(locale.LC_ALL, 'de_DE')
        return locale.format_string("%.2f", value, grouping=True)