使用 F 字符串显示浮点数
Displaying floats using F-string
我很好奇为什么将这个“f”添加到我要显示的数字末尾时行为如此不同:
# CASE with f
float1 = 10.1444786
print(f"{float1:.4f}")
# print out: 10.1445
# CASE without f
print(f"{float1:.4}")
# print out: 10.14
为什么第二个例子只显示了2个字符?
隐含的类型说明符是 g
,如 documentation Thanks @Barmar for adding a 中给出的信息!
None: For float
this is the same as 'g', except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully.
For Decimal
, this is the same as either 'g' or 'G' depending on the value of context.capitals for the current decimal context.
The overall effect is to match the output of str()
as altered by the other format modifiers.
一个实验:
for _ in range(10000):
r = random.random() * random.randint(1, 10)
assert f"{r:.6}" == f"{r:.6g}"
每次都有效
来自 https://docs.python.org/3/library/string.html#formatstrings、
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.
因此,在您的第二个示例中,您要求 4 个 sigfigs,但在您的第一个示例中,您要求 4 位精度。
我很好奇为什么将这个“f”添加到我要显示的数字末尾时行为如此不同:
# CASE with f
float1 = 10.1444786
print(f"{float1:.4f}")
# print out: 10.1445
# CASE without f
print(f"{float1:.4}")
# print out: 10.14
为什么第二个例子只显示了2个字符?
隐含的类型说明符是 g
,如 documentation Thanks @Barmar for adding a
None: For
float
this is the same as 'g', except that when fixed-point notation is used to format the result, it always includes at least one digit past the decimal point. The precision used is as large as needed to represent the given value faithfully.For
Decimal
, this is the same as either 'g' or 'G' depending on the value of context.capitals for the current decimal context.The overall effect is to match the output of
str()
as altered by the other format modifiers.
一个实验:
for _ in range(10000):
r = random.random() * random.randint(1, 10)
assert f"{r:.6}" == f"{r:.6g}"
每次都有效
来自 https://docs.python.org/3/library/string.html#formatstrings、
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.
因此,在您的第二个示例中,您要求 4 个 sigfigs,但在您的第一个示例中,您要求 4 位精度。