exponential float formmating
attn.steven.kuo at gmail.com
attn.steven.kuo at gmail.com
Fri Sep 7 11:03:09 EDT 2007
On Sep 7, 6:08 am, zunbe... at gmail.com wrote:
> Hi,
>
> For compatibility reasons with an old program I have to format string
> in exponential
> format with the following format
>
> 0.xxxxxE-yy
>
> This means that the number start always by 0 and after the exponent
> there should be alway the sing and 2 number for the exponent.
>
> for example 13 shoud be 0.13000E+02
> I always get 1.30000E001
>
Perhaps it would then be worthwhile to subclass float?
import math
class ffloat(float):
"""Formatted float?"""
def __str__(self):
prefix = (self < 0) and '-' or ''
fabs = math.fabs(self)
exponent = math.floor(math.log10(fabs)) + 1
significand = fabs / math.pow(10, exponent)
width = exponent > 0 and 2 or 3
return '%s%fE%0*d' % (prefix,significand,width,exponent)
f = ffloat(13)
print f
f = ffloat(-12.23e-4)
print f
--
Hope this helps,
Steven
More information about the Python-list
mailing list