unusual exponential formatting puzzle

Michael Spencer mahs at telcopartners.com
Wed Sep 21 17:32:53 EDT 2005


Neal Becker wrote:
> Like a puzzle?  I need to interface python output to some strange old
> program.  It wants to see numbers formatted as:
> 
> e.g.: 0.23456789E01
> 
> That is, the leading digit is always 0, instead of the first significant
> digit.  It is fixed width.  I can almost get it with '% 16.9E', but not
> quite.
> 
> My solution is to print to a string with the '% 16.9E' format, then parse it
> with re to pick off the pieces and fix it up.  Pretty ugly.  Any better
> ideas?
> 
> 
Does this do what you want?

  >>> from math import log10, modf, fabs
  >>> def format(n, mantplaces = 9, expplaces = 2):
  ...     sign, n = n/fabs(n), fabs(n)    # preserve the sign
  ...     c, m = modf(log10(n))
  ...     c, m = c - (c>0), m + (c>0)     # redistribute mantissa to exponent
  ...     return "%.*fE%0*d" % (mantplaces, sign * 10**c, expplaces, m)
  ...
  >>>
  >>> def test_format(n):
  ...     for  exp in range(-5, 5):
  ...         N = n*(10**exp)
  ...         print format(n*(10**exp))
  ...
  >>> test_format(234.56789)
  0.234567890E-2
  0.234567890E-1
  0.234567890E00
  0.234567890E01
  0.234567890E02
  0.234567890E03
  0.234567890E04
  0.234567890E05
  0.234567890E06
  0.234567890E07
  >>>

Michael




More information about the Python-list mailing list