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
  • 19,232
  • 5
  • 47
  • 69
Kevin Kostlan
  • 3,311
  • 7
  • 29
  • 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,406
  • 2
  • 36
  • 55
1
precision = 2
number_to_convert = 10000
print "%0.*e"%(precision,number_to_convert)

is that what you are asking for?

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
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
  • 398,270
  • 210
  • 566
  • 880