"rounding" a negative exponent in python

I want to convert some small numbers into simple, readable output. Here is my method, but I wonder if there is something simpler.

x = 8.54768039530728989343156856E-58
y = str(x)
print "{0}.e{1}".format(y.split(".")[0], y.split("e")[1])
8.e-58
+3
source share
4 answers

It's pretty close, do you need it for 8.e-58sure or are you just trying to cut it down to something readable?

>>> x = 8.54768039530728989343156856E-58
>>> print "{0:.1e}".format(x)
8.5e-58

Alternative:

>>> print "{0:.0e}".format(x)
9e-58

Note that in Python 2.7 or 3.1+ you can omit the first zero that indicates the position, so this will be something like "{:.1e}".format(x)

+4
source

like this?

>>> x = 8.54768039530728989343156856E-58
>>> "{:.1e}".format(x)
'8.5e-58'
+3
source

, - .

def frexp_10(decimal):
   logdecimal = math.log10(decimal)
   return 10 ** (logdecimal - int(logdecimal)), int(logdecimal)

>>> frexp_10(x)
(0.85476803953073244, -57)

...

+1

: .

:

>>> round(3.1415,2)
3.14
>>> round(1.2345678e-10, 12)
1.23e-10

round() . , .

To display, it is important which version of the display you are using. In Python 2.x and deprecated in 3.x you can use the 'e' formatting.

>>> print "%6.2e" % 1.2345678e-10
1.23e-10

or in 3.x, use:

>>> print("{:12.2e}".format(3.1415))
    3.14e+00
>>> print("{:12.2e}".format(1.23456789e-10))
    1.23e-10

or if you like zeros:

>>> print("{:18.14f}".format(1.23456789e-10))
  0.00000000012346
0
source

All Articles