On 2:59 PM, Richard D. Moores wrote:
It's great to have you chime in, Steven. I do wish you would stop
pulling your punches, however. ;)

On Fri, Oct 22, 2010 at 17:23, Steven D'Aprano<st...@pearwood.info>  wrote:
On Sat, 23 Oct 2010 12:42:50 am Richard D. Moores wrote:

So I wrote a function:

def float2n_decimals(floatt, n):
     """
     Given a float (floatt), return floatt to n decimal places.

     E.g., with n =, 81.34567 ->  81.35
     """
     return ("%%.%sf" % n) % floatt

which works fine,

float2n_decimals(x, 3)

is better written in place as:

"%.*f" % (3, x)

There's no need for a function for something so simple.
Yes, but I needed one for ("%%.%sf" % n) % floatt .

<snip>

Sometimes Steven's style can be a bit caustic, but there's almost always a few important nuggets. In this case, you missed the one that your formatting is unnecessarily complicated, at least if you have a recent enough Python version.

In particular,
     "%.*f" % (n, myfloat)

will convert myfloat to a string, and use n as the precision, just as your more complex expression. The asterisk is the magic character, that says use n as the precision field.

This syntax was available at least in 2.3, so unless you need to use an older version, there's not much need for the two-stage template system.

DaveA

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to