我想格式化一个精度为参数的 float
"{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 theformat_spec
are substituted before theformat_spec
string is interpreted. This allows the formatting of a value to be dynamically specified.
关于python - 将精度作为参数传递给 python 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28590494/