round exponential float to 2 decimals

时间秒杀一切 提交于 2019-12-07 17:13:43

问题


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


回答1:


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'


来源:https://stackoverflow.com/questions/24118366/round-exponential-float-to-2-decimals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!