- 1 year ago
How to make that f"..." string formatting uses comma instead of dot as decimal separator?
Comment
1 / 1
You can use the locale
module in Python to set the decimal separator to comma instead of dot. Here is an example:
pythonimport locale
# Set the decimal separator to comma
locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')
# Use f-string with comma as decimal separator
a = 12.345
b = f"{a:.2f}"
print(b) # Output: "12,35"
In this example, locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')
sets the locale to French, which uses a comma as the decimal separator. Then, f"{a:.2f}"
formats the float a
with two decimal places and a comma as the decimal separator. The output is "12,35"
.
Note that the locale needs to be installed on your system in order to use it. If the locale is not installed, you will get an exception.