Python f-strings是否有一种简单的方法来修复小数点后的位数? (特别是 f 字符串,而不是其他字符串格式化选项,如 .format 或 %)
例如,假设我想显示小数点后 2 位。
我怎么做?让我们这么说
a = 10.1234
原文由 GafferMan2112 发布,翻译遵循 CC BY-SA 4.0 许可协议
Python f-strings是否有一种简单的方法来修复小数点后的位数? (特别是 f 字符串,而不是其他字符串格式化选项,如 .format 或 %)
例如,假设我想显示小数点后 2 位。
我怎么做?让我们这么说
a = 10.1234
原文由 GafferMan2112 发布,翻译遵循 CC BY-SA 4.0 许可协议
当涉及到 float
数字时,您可以使用 格式说明符:
f'{value:{width}.{precision}}'
在哪里:
value
是计算结果为数字的任何表达式width
指定用于显示的字符总数,但如果 value
需要比宽度指定更多的空间,则使用额外的空间。precision
表示小数点后使用的字符数您缺少的是十进制值的类型说明符。在此 链接 中,您可以找到浮点数和小数的可用表示类型。
这里有一些示例,使用 f
(定点)表示类型:
# notice that it adds spaces to reach the number of characters specified by width
In [1]: f'{1 + 3 * 1.5:10.3f}'
Out[1]: ' 5.500'
# notice that it uses more characters than the ones specified in width
In [2]: f'{3000 + 3 ** (1 / 2):2.1f}'
Out[2]: '3001.7'
In [3]: f'{1.2345 + 4 ** (1 / 2):9.6f}'
Out[3]: ' 3.234500'
# omitting width but providing precision will use the required characters to display the number with the the specified decimal places
In [4]: f'{1.2345 + 3 * 2:.3f}'
Out[4]: '7.234'
# not specifying the format will display the number with as many digits as Python calculates
In [5]: f'{1.2345 + 3 * 0.5}'
Out[5]: '2.7344999999999997'
原文由 lmiguelvargasf 发布,翻译遵循 CC BY-SA 4.0 许可协议
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
1 回答3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.5k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
在格式表达式中包含类型说明符: