[Tutor] How to convert a long decimal into a string?

Dick Moores rdm at rcblue.com
Tue Jan 16 22:57:47 CET 2007


At 12:47 PM 1/16/2007, you wrote:
>On Tue, 2007-01-16 at 12:28 -0800, Dick Moores wrote:
> > So I go with working up "an algorithm for first
> > converting n to an int (for
> > example, multiplying the above n by 1000), converting to a string,
> > putting the decimal point back in between indices 2 and 3, then using
> > that string as n (thereby avoiding the use of quotes around n as the
> > first argument)."
>
>This seems like a lot of effort for not much reward.  Where is n coming
>from?  If you already have something that holds the required level of
>precision, why does it need to be transformed?  Could it already be a
>string?  If n is entered through raw_input, then you received it as a
>string.
>
>I don't want to push you in the wrong direction, but it seems like there
>must be a better way.

LLoyd, Yes, that's right, isn't it. And functions I would use that 
feed into numberRounding() would be things such as my decPow(), which 
returns a string:   (All corrective comments on it are welcome!)
==============================
def decPow(n, power, precision=40):
         """
         Raise any number n (as a string) to any integral power,
         to any degree of precision.
         """
         import decimal
         def d(x):
                 return decimal.Decimal(str(x))

         if power == 0:
                 return 1
         elif power > 0:
                 decimal.getcontext().prec = precision
                 product = d(n)
                 for k in range(1,power):
                         product = product * d(n)
                 return product
         elif power < 0:
                 decimal.getcontext().prec = precision
                 quotient = 1/d(n)
                 for k in range(1, -(power)):
                         quotient = quotient / d(n)
                 return quotient
================================

Still, I'd like to see if can write that algorithm. ;)

Thanks very much,

Dick





More information about the Tutor mailing list