简体   繁体   中英

round exponential float to 2 decimals

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM