Passing precision as parameter to python format
python, python-2.7, string, string-formatting
Solution
You can nest the format fields to dynamically specify the precision:
>>> "{1:,.{0}f}$".format(2, 1000 + 1/float(3))
'1,000.33$'
>>>
From the docs:
A `format_spec` field can also include nested replacement fields within it. These nested replacement fields can contain only a field name; conversion flags and format specifications are not allowed. The replacement fields within the `format_spec` are substituted before the `format_spec` string is interpreted. This allows the formatting of a value to be dynamically specified.
Problem
I want to format a float with the precision as parameter ``` "{0:,.2f}$".format(1000 + 1/float(3)) '1,000.33$' ``` How can I pass the number of decimal places (`.2f`) as parameter ? Just for reference, I know I can use `round(n,precision)` but then when `precision=0` it prints `0.0` which is not what I want. I can also concatenate like `"{0:,." + str(precision) + "2f}f".format(n)` but you know ...