-1

I can convert floats to scientific notations in python 3.6 in the following way:

from decimal import Decimal
a = 0.00235
b = "{:.4e}".format(Decimal(a))

which outputs:

2.3500e-3

However, what I need is this output:

2.3500e-003

I can't figure out how to do this. Any ideas?

Matina G
  • 1,452
  • 2
  • 14
  • 28

1 Answers1

1

you can use:

def eformat(f, prec, exp_digits):
    s = "%.*e"%(prec, f)
    mantissa, exp = s.split('e')
    # add 1 to digits as 1 is taken by sign +/-
    return "%se%+0*d"%(mantissa, exp_digits+1, int(exp))

print(eformat(0.00235, 5, 3))

which outputs:

2.35000e-003

David
  • 8,113
  • 2
  • 17
  • 36