0

I have a normal float number such as "1234.567" or "100000". I would like to convert it to a string such that the precision is fixed and the number is in scientific notation. For example, with 5 digits, the results would be "1.2346e003 and "1.0000e005", respectively. The builtin Decimal number -> string functions will round it if it can, so the second number would be only "1e005" even when I want more digits. This is undesirable since I need all numbers to be the same length.

Is there a "pythonic" way to do this without resorting to complicated string operations?

3 Answers 3

1
precision = 2
number_to_convert = 10000
print "%0.*e"%(precision,number_to_convert)

is that what you are asking for?

1

You can use the %e string formatter:

>>> '%1.5e'%1234.567
'1.23457e+03'

>>> "%1.5e"%100000
'1.00000e+05'

%x.ye where x = min characters and y = max precision.

2
  • ahhh you fixed it before I posted ... (+1) May 29, 2014 at 19:40
  • Yeah I missed the same length part for whatever reason. All good thx.
    – woot
    May 29, 2014 at 19:43
1

If you need to keep the 3-digit exponent like in your example, you can define your own function. Here's an example adapted from this answer:

def eformat(f, prec, exp_digits):
    s = "%.*e"%(prec, f)
    mantissa, exp = s.split('e')
    return "%se%0*d"%(mantissa, exp_digits, int(exp))

>>> print eformat(1234.567, 4, 3)
1.2346e003
1
  • yes a three digit is good because 1e200 is not longer than 1e20. May 30, 2014 at 1:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.