unusual exponential formatting puzzle

mensanator at aol.com mensanator at aol.com
Wed Sep 21 16:07:31 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?

If you have gmpy available...

>>> import gmpy

...and your floats are mpf's...

>>> s = gmpy.pi(64)
>>> s
mpf('3.14159265358979323846e0',64)

...you can use the fdigits function

>>> t = gmpy.fdigits(s,10,8,0,0,2)

...to create a seperate digit string and exponent...

>>> print t
('31415927', 1, 64)

...which can then be printed in the desired format.

>>> print "0.%sE%02d" % (t[0],t[1])
0.31415927E01




More information about the Python-list mailing list