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
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.
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.
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).
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With