[Tutor] Some questions about my yen-USD.py

Dick Moores rdm at rcblue.com
Fri Sep 8 05:06:08 CEST 2006


At 05:37 AM 9/7/2006, Andrei wrote:
>Dick Moores <rdm <at> rcblue.com> writes:
>
> > (2) Is my roundingN() function OK? Is there a better way to write it?
> > Will the line
> >
> >         n = round(float(n)*(10**rounding))/(10**rounding)
>
>Using format strings is easier I think. "%.2f" % 2.34234 will give '2.34'.

I had mistakenly believed that format strings could be used only in 
print expressions!

So now that I know better, I'm trying to write the beginnings of a 
general setPrecision() function using format strings. However, it 
appears that a variable cannot be used instead of the ".2" in

"%.2f" % 2.234234

def setPrecision(n, precision):
   n = str(n)
       p = precision
       if "." in n:
          n = "%.pf" % float(n)
          n = str(n)
          return n

n = 2.234234
precision = 2
print setPrecision(n, precision)

This get the error:
ValueError: unsupported format character 'p' (0x70) at index 2

How to do this?

Dick



More information about the Tutor mailing list