14

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

Community
  • 1
  • 1
Leszek
  • 1,290
  • 2
  • 11
  • 21
  • 3
    `"%.3g" % 4.311237638482733e-91 --> '4.31e-91'` `f` is *not* the only way to format a float. see [here](https://docs.python.org/2/library/stdtypes.html#string-formatting). Also `str.format` is more powerful. – Bakuriu Jun 09 '14 at 10:37
  • 3
    `format(4.311237638482733e-91, '.2e')`?? – Ashwini Chaudhary Jun 09 '14 at 10:38
  • @Bakuriu I'm happy to accept your comment as an answer, but you will need to write it as the answer;) – Leszek Jun 10 '14 at 09:41
  • @Leszek I didn't answer immediately because the question was closed as duplicate, and I didn't want to reopen it immediately before further checking... and then I forgot about it :) – Bakuriu Jun 10 '14 at 11:19

1 Answers1

20

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'
Bakuriu
  • 98,325
  • 22
  • 197
  • 231