使用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,如文档中所示 感谢@Barmar添加带有此信息的评论!

无:因为float这与 'g' 相同,除了当使用定点表示法来格式化结果时,它总是至少包含小数点后的一位。使用的精度与忠实地表示给定值所需的一样大。

对于Decimal,这与 'g' 或 'G' 相同,具体取决于当前十进制上下文的 context.capitals 值。

整体效果是匹配str()由其他格式修饰符更改的输出。

一个实验:

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,

一般格式。对于给定的精度 p >= 1,这会将数字四舍五入为 p 位有效数字,然后根据其大小将结果格式化为定点格式或科学记数法。精度 0 被视为等同于精度 1。

所以在你的第二个例子中,你要求 4 个 sigfigs,但在你的第一个例子中,你要求 4 位精度。

  • This is stated in the [documentation](https://docs.python.org/3/library/string.html#format-specification-mini-language): **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.**

以上是使用F-string显示浮点数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>