简体   繁体   中英

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?

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

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 'g', except that it uses the current locale setting to insert the appropriate number separator characters.

Whereas 'g' is described at:

g General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. A precision of 0 is treated as equivalent to a precision of 1. ...Truncated...

The 'f' description is:

'f' Fixed-point notation. For a given precision p, formats the number as a decimal number with exactly p digits following the decimal point.

You can use "locale.format_string" instead of "f string"

Try this instead:

import locale
# Set the locale to "french"
locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
# Format the number 3.14 with 2 decimal places, using the french locale
print(locale.format_string("%.2f", 3.14, grouping=True))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM