Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 928
Leszek Avatar asked Jun 09 '14 10:06

Leszek


People also ask

How do you round a float to two decimal places?

This is a two step process: Multiply the number by 100 and round the result down to the nearest integer. Divide the result by 100 to round down the float to 2 decimal places.

How do you round off exponential value?

The exponential numbers are also called scientific numbers and these numbers have exponent representation by the letter e. For example, a number 12340000 can be represented as 1.234e + 107. We can round this to 1.2e + 107 and in R it can be done with the help of singif function.

How do you round to 2 decimal places in Excel?

For example: If you wanted to use the number from cell A2 and have it rounded to two decimal places, you could enter =ROUND(A2,2). Or, if you want to divide cell B2 by cell C2, and round the result to 3 decimals, you would use =ROUND(B2/C2,3).


1 Answers

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'
like image 93
Bakuriu Avatar answered Oct 13 '22 01:10

Bakuriu