Search code examples
pythonfloating-pointformatf-string

How to format a float with a comma as decimal separator in an f-string?


For some machine control in python, I write the results to a text-file, that someone else can copy into Excel (this is the most convenient way in this situation). However, in the Netherlands, Excel has a comma as decimal separator and thus I want to have the result "position" in the text-file as 123,456, but when I use the f-string method like this:

    resultfile.write(f"Position\t{position:.5}")

This will obviously result in a dot decimal separator.

How can I change this to a comma without iterating through the whole file int the end and replace the dots with commas?


Solution

  • If you want to format floats with a comma within the f-string, you can either use replace after casting the float to a string:

    position = 123.456
    f"Position\t{str(position).replace('.',',')}"
    

    A second option is to use the Python standard library module locale (but it is not thread-safe):

    import locale
    locale.setlocale(locale.LC_ALL, 'nl_NL')
    f"Position\t{locale.format('%.3f', position)}"
    

    A third option is to use the library babel (preferred in case of library routines):

    from babel.numbers import format_decimal
    f"Position\t{format_decimal(position, locale='nl_NL')}"
    

    All three options return the same result for the given example:

    'Position\t123,456'