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
if x == 0.0: return f" {x:.{n}e}"
to if x == 0.0: return " {0:.{1}e}".format(x, n)
and return s + f"{z:.{n}f}e{m:+03d}"
to return s + "{0:.{1}f}e{2:+03d}".format(z, n,int(m))
and it will be Python 2.7 compatible.
Commented
Jul 5 at 14:52
You could do something like the following:
import math
x = 0.07365
def zero_one_mant(x):
"""
Return a string for the input number `x`, where the mantissa is always
between 0 and 1 and the exponent is adjusted accordingly.
"""
exp = int(math.floor(math.log10(x))) + 1
mant = x / 10**exp
return "{0:.6f}e{1:+03d}".format(mant, exp)
for x in [0.07365, 7.365, 73.65]:
print(zero_one_mant(x))
0.736500e-01
0.736500e01
0.736500e02
1.000000e...
be included or excluded?