[Tutor] Some questions about my yen-USD.py
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 : '%.*f' % (2, 2.234234)
In : '%.*f' % (4, 2.234234)
You can do this with the width parameter also which can be very useful
when you have computed a field width:
In : '%*s' % (4, 'foo')
Out: ' foo'
In : '%*s' % (10, 'foo')
Out: ' foo'
More information about the Tutor