I want to format a number so that the mantissa is between 0 and 1 instead of 1 and 10 in scientific notation.
For example;
a=7.365
print("{:.6e}".format(a))
This will output 7.365000e+00
, but I want it to be 0.736500e+01
.
I suppose you could always try constructing your own preformatted string. (No idea if this works in Python 2.7, though).
import math
def fixit( x, n ):
if x == 0.0: return f" {x:.{n}e}"
s = ' ' if x >= 0 else '-'
y = math.log10( abs(x) )
m = math.floor(y) + 1
z = 10 ** ( y - m )
return s + f"{z:.{n}f}e{m:+03d}"
for x in [ -7635, -763.5, -76.35, -7.635, -0.7635, -0.07635, -0.007635, 0.007635, 0.07635, 0.7635, 7.635, 76.35, 763.5, 7635 ]:
print( fixit( x, 6 ) )
for x in [ -10, -1, -0.1, -0.01, 0.0, 0.01, 0.1, 1, 10 ]:
print( fixit( x, 6 ) )
Output:
-0.763500e+04
-0.763500e+03
-0.763500e+02
-0.763500e+01
-0.763500e+00
-0.763500e-01
-0.763500e-02
0.763500e-02
0.763500e-01
0.763500e+00
0.763500e+01
0.763500e+02
0.763500e+03
0.763500e+04
-0.100000e+02
-0.100000e+01
-0.100000e+00
-0.100000e-01
0.000000e+00
0.100000e-01
0.100000e+00
0.100000e+01
0.100000e+02