[Tutor] Some questions about my yen-USD.py
Kent Johnson
kent37 at tds.net
Fri Sep 8 13:52:35 CEST 2006
Dick Moores wrote:
> 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
Yes, it can, just not the way you think - if you use a * for the
precision, the value will be read from the provided parameters:
In [1]: '%.*f' % (2, 2.234234)
Out[1]: '2.23'
In [2]: '%.*f' % (4, 2.234234)
Out[2]: '2.2342'
You can do this with the width parameter also which can be very useful
when you have computed a field width:
In [3]: '%*s' % (4, 'foo')
Out[3]: ' foo'
In [4]: '%*s' % (10, 'foo')
Out[4]: ' foo'
Kent
More information about the Tutor
mailing list