[英]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
.但是 output 是
3.14
而我想要3,14
。
How to do this with f"..." string formatting?如何使用 f"..." 字符串格式来做到这一点?
Note: I don't want to use .replace(".", ",")
注意:我不想使用
.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?注意:我正在寻找 Windows 解决方案,以及来自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):
不起作用(因此它在 Windows 上不是重复的):
locale.setlocale(locale.LC_ALL, 'nl_NL')
# or
locale.setlocale(locale.LC_ALL, 'fr_FR')
locale.Error: unsupported locale setting
locale.Error:不支持的区域设置
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
将
print(f"{3.14:.2f}")
更改为print(f"{3.14:.3n}")
,您将得到结果: 3,14
See https://docs.python.org/3/library/string.html#format-specification-mini-language :请参阅https://docs.python.org/3/library/string.html#format-specification-mini-language :
'n'
Number.'n'
号。 This is the same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.这与“g”相同,只是它使用当前区域设置来插入适当的数字分隔符。
Whereas 'g'
is described at:而
'g'
描述于:
g
General format.g
通用格式。 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.对于给定的精度 p >= 1,这会将数字四舍五入为 p 位有效数字,然后根据其大小将结果格式化为定点格式或科学记数法。 A precision of 0 is treated as equivalent to a precision of 1. ...Truncated...
精度为 0 被视为等同于精度为 1。...截断...
The 'f'
description is: 'f'
描述是:
'f'
Fixed-point notation.'f'
定点符号。 For a given precision p, formats the number as a decimal number with exactly p digits following the decimal point.对于给定的精度 p,将数字格式化为小数点后正好有 p 位的十进制数。
You can use "locale.format_string" instead of "f string"您可以使用“locale.format_string”而不是“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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.