Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make that f"…" string formatting uses comma instead of dot as decimal separator?

I tried:

import locale
print(locale.locale_alias)
locale.setlocale(locale.LC_ALL, '')
locale.setlocale(locale.LC_NUMERIC, "french")
print(f"{3.14:.2f}")

but the output is 3.14 whereas I would like 3,14.

How to do this with f"…" string formatting?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Note: I don’t want to use .replace(".", ",")

Note: I’m looking for a Windows solution, and solutions from How to format a float with a comma as decimal separator in an f-string? don’t work (thus it’s not a duplicate on Windows):

locale.setlocale(locale.LC_ALL, 'nl_NL')
# or
locale.setlocale(locale.LC_ALL, 'fr_FR')

locale.Error: unsupported locale setting

>Solution :

I looked up the answers on the duplicate flagged page and found an answer that worked:

Change print(f"{3.14:.2f}") to print(f"{3.14:.3n}") and you will get the result: 3,14

See https://docs.python.org/3/library/string.html#format-specification-mini-language:

'n' : Number. This is the same as ‘d’, except that it uses the current locale setting to insert the appropriate number separator characters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading