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?

Andy G
  • 18,826
  • 5
  • 45
  • 66
Kevin Kostlan
  • 3,049
  • 6
  • 26
  • 33

3 Answers3

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.

woot
  • 7,202
  • 2
  • 35
  • 54
1
precision = 2
number_to_convert = 10000
print "%0.*e"%(precision,number_to_convert)

is that what you are asking for?

Joran Beasley
  • 103,130
  • 11
  • 146
  • 174
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
Community
  • 1
  • 1
Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861