使用 f 字符串固定小数点后的数字

新手上路,请多包涵

Python f-strings是否有一种简单的方法来修复小数点后的位数? (特别是 f 字符串,而不是其他字符串格式化选项,如 .format 或 %)

例如,假设我想显示小数点后 2 位。

我怎么做?让我们这么说

a = 10.1234

原文由 GafferMan2112 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 522
2 个回答

在格式表达式中包含类型说明符:

 >>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

原文由 Robᵩ 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题