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 = 2, 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. > but a question remains: n is an integer. Why the > 's' in '%sf'? Your function might be more clear if you split the formatting into two lines: template = "%%.%sf" % n return template % floatt The first line builds a template string from n. Now it becomes clear what %s is for: it's to insert the n as a string into the template. %d would express the intention of the function better. By the way, the function docstring is seriously misleading. It describes a completely different function: > Given a float (floatt), return floatt to n decimal places. > > E.g., with n = 2, 81.34567 -> 81.35 It does nothing of the sort! What you are describing is the built-in function round: >>> print round(81.34567, 2) 81.35 What your function does is return a string, not a float. Besides, given a float, where does n come from? A global variable? There is a convention for giving examples that you should follow. Putting the three of these together, your docstring should say something like: Given a float floatt and an integer n, returns floatt formatted as a string to n decimal places. >>> float2n_decimals(2, 81.34567) '81.35' (BTW, I really hate the name "floatt". It makes me think you're stuttering.) -- Steven D'Aprano _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor