Python 如何从变量中指定浮点十进制精度?

Python 如何从变量中指定浮点十进制精度?,python,string,floating-point,floating-point-precision,Python,String,Floating Point,Floating Point Precision,我将以下重复的简单代码重复多次,我想为其创建一个函数: for i in range(10): id = "some id string looked up in dict" val = 63.4568900932840928 # some floating point number in dict corresponding to "id" tabStr += '%-15s = %6.1f\n' % (id,val) 我希望能够调用此函数:def printStr(

我将以下重复的简单代码重复多次,我想为其创建一个函数:

for i in range(10):
    id  = "some id string looked up in dict"
    val = 63.4568900932840928 # some floating point number in dict corresponding to "id"
    tabStr += '%-15s = %6.1f\n' % (id,val)
我希望能够调用此函数:
def printStr(precision)

其中,它执行上述代码,并将
tabStr
val
返回到
precision
小数点

例如:
printStr(3)

对于
tabStr
中的
val
将返回
63.457

有没有办法实现这种功能

tabStr += '%-15s = %6.*f\n' % (id, i, val)  
其中
i
是小数位数


顺便说一句,在最近的Python中,
.format()
已经取代了
%
,您可以使用

"{0:<15} = {2:6.{1}f}".format(id, i, val)
“{0:这也应该可以

tabStr += '%-15s = ' % id + str(round(val, i))

其中,
i
是所需的精度。

我知道这是一个旧线程,但有一种更简单的方法:

试试这个:

def printStr(FloatNumber, Precision):
    return "%0.*f" % (Precision, FloatNumber)
tabStr += '%-15s = ' % id + str(round(val, i))
def printStr(FloatNumber, Precision):
    return "%0.*f" % (Precision, FloatNumber)