将指数浮点数舍入到小数点后两位 [英] round exponential float to 2 decimals
问题描述
我想在 Python 中将指数浮点数四舍五入为两位十进制表示.
4.311237638482733e-91 -->4.31e-91
你知道有什么快速的技巧可以做到这一点吗?
像 round(float, 2)
和 "%.2f"%float
这样的简单解决方案不适用于指数浮点数:/
这不是关于舍入浮点数,而是舍入指数浮点数,因此它与 如何在 Python 中将数字四舍五入为有效数字
您可以使用 g
格式说明符,它根据精度在指数和通常"表示法之间进行选择,并指定有效位数:
如果您想始终以指数表示法表示数字,请使用 e
格式说明符,而 f
从不 使用指数表示法.此处描述了完整的可能性列表.
另请注意,您可以使用 str.format
代替 %
样式的格式:
str.format
比 %
风格的格式更强大、更可定制,也更一致.例如:
如果您不喜欢在字符串文字上调用方法,您可以使用 format
内置函数:
I want to round exponential float to two decimal representation in Python.
4.311237638482733e-91 --> 4.31e-91
Do you know any quick trick to do that?
Simple solutions like round(float, 2)
and "%.2f"%float
are not working with exponential floats:/
EDIT: It's not about rounding float, but rounding exponential float, thus it's not the same question as How to round a number to significant figures in Python
You can use the g
format specifier, which chooses between the exponential and the "usual" notation based on the precision, and specify the number of significant digits:
>>> "%.3g" % 4.311237638482733e-91
'4.31e-91'
If you want to always represent the number in exponential notation use the e
format specifier, while f
never uses the exponential notation. The full list of possibilities is described here.
Also note that instead of %
-style formatting you could use str.format
:
>>> '{:.3g}'.format(4.311237638482733e-91)
'4.31e-91'
str.format
is more powerful and customizable than %
-style formatting, and it is also more consistent. For example:
>>> '' % []
''
>>> '' % set()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>> ''.format([])
''
>>> ''.format(set())
''
If you don't like calling a method on a string literal you can use the format
built-in function:
>>> format(4.311237638482733e-91, '.3g')
'4.31e-91'
这篇关于将指数浮点数舍入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!