gpt4 book ai didi

python - 将指数 float 舍入为 2 位小数

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:10 25 4
gpt4 key购买 nike

我想在 Python 中将指数 float 四舍五入为两位小数。

4.311237638482733e-91 --> 4.31e-91

你知道什么快速技巧吗?
round(float, 2)"%.2f"%float 等简单解决方案不适用于指数 float :/

编辑:这不是关于舍入 float ,而是舍入指数 float ,因此它与 How to round a number to significant figures in Python 不是同一个问题。

最佳答案

您可以使用 g 格式说明符,它根据精度在指数表示法和“通常”表示法之间进行选择,并指定有效位数:

>>> "%.3g" % 4.311237638482733e-91
'4.31e-91'

如果您想始终以指数表示法表示数字,请使用 e 格式说明符,而 f 从不 使用指数表示法。描述了完整的可能性列表 here .

另请注意,您可以使用 str.format 而不是 % 格式:

>>> '{:.3g}'.format(4.311237638482733e-91)
'4.31e-91'

str.format% 风格的格式更强大和可定制,而且也更一致。例如:

>>> '' % []
''
>>> '' % set()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>> ''.format([])
''
>>> ''.format(set())
''

如果您不喜欢在字符串文字上调用方法,您可以使用 format内置函数:

>>> format(4.311237638482733e-91, '.3g')
'4.31e-91'

关于python - 将指数 float 舍入为 2 位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24118366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com