force non-exponential representation for Decimal?
Mensanator
mensanator at aol.com
Wed Dec 23 16:06:40 EST 2009
On Dec 23, 4:03 am, jh... at gmx.de wrote:
> (cc-ing the list)
>
> > > Is there a convenient way to force a decimal.Decimal representation to
> > not use exponential representation?
>
> > Which Python version are you using? For Python 2.6 (and 3.1), the
> > answer's yes. For earlier Python verions, I don't think so. In
> > Python 2.6, use new-style formatting with the 'f' modifier:
>
> > >>> '{0:f}'.format(Decimal('1e-100'))
> > '0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001'
> > >>> '{0:f}'.format(Decimal('1e100'))
> > '10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
>
> Unfortunately, I'm still using Python 2.4 so I can't go that way (at least not anytime soon, this is a production environment).
But you can get gmpy for Python 2.4. And then you can do:
>>> c = gmpy.mpf('2.3430000000837483727772E-19')
>>> c
mpf('2.34300000008374837278e-19')
>>> help(gmpy.fdigits)
Help on built-in function fdigits in module gmpy:
fdigits(...)
fdigits(x, base=10, digs=0, mine=0, maxe=-1, opts=0): formats x,
which is an mpf or else gets coerced to one.
Returns up to digs digits in the given base (if digs is 0, as many
digits as are available), but no more than available given x's
precision; the resulting string is formatted in fixed point
if the exponent is >=mine and <=maxe, else in exponential (the
exponent-separator is 'e' for base up to 10, else '@' -- the
exponent is always output as a signed, base-10 integer). If opts
has bit 1 set, the whole is wrapped in 'gmpy.mpf(...)', to ease
later approximate reconstruction via builtin function eval
(Or, in just mpf(...) if gmpy.set_tagoff(1) was called).
If opts has bit 2 set, then opts bit 1, mine, and maxe, are
ignored; the result is then a 2-element tuple, first element
the raw string of base-digits without formatting, second the
exponent in base as a Python int.
>>> gmpy.fdigits(c,10,30,-30,30)
'0.000000000000000000234300000008374837278'
>
> > For earlier Python versions, you can manipulate the output string as
> > you describe, or you can extract the raw components of the Decimal
> > instance (e.g. with the as_tuple() method) and construct a string
> > directly from those. You might be also be able to extract code for
> > the '{:f}' formatting from the Python 2.6 Decimal source (Lib/
> > decimal.py), but it's fairly convoluted.
>
> Thanks a lot for the hints, I'll look into that.
>
> Holger
>
> --
> GRATIS für alle GMX-Mitglieder: Die maxdome Movie-FLAT!
> Jetzt freischalten unterhttp://portal.gmx.net/de/go/maxdome01
More information about the Python-list
mailing list