将精度作为参数传递给 python 格式

Passing precision as parameter to python format

我想格式化一个精度为参数的浮点数

"{0:,.2f}$".format(1000 + 1/float(3))
'1,000.33$'

如何将小数位数 (.2f) 作为参数传递?

仅供参考,我知道我可以使用 round(n,precision) 但是当 precision=0 时它打印 0.0 这不是我想要的。我也可以像 "{0:,." + str(precision) + "2f}f".format(n) 这样连接,但你知道......

您可以嵌套格式字段以动态指定精度:

>>> "{1:,.{0}f}$".format(2, 1000 + 1/float(3))
'1,000.33$'
>>>

来自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.