如何从变量中指定浮点小数精度?

时间:2021-06-26 16:56:47

I have the following repetitive simple code repeated several times that I would like to make a function for:

我有以下重复的简单代码几次,我想为:

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)

I want to be able to call this function: def printStr(precision)
Where it preforms the code above and returns tabStr with val to precision decimal points.

我想要能够调用这个函数:def printStr(precision),它在其中预生成上面的代码,并返回带有val的表str到精确小数点。

For example: printStr(3)
would return 63.457 for val in tabStr.

例如:printStr(3)将为tabStr中的val返回63.457。

Any ideas how to accomplish this kind of functionality?

有什么想法可以实现这种功能吗?

3 个解决方案

#1


27  

tabStr += '%-15s = %6.*f\n' % (id, i, val)  

where i is the number of decimal places.

这里是小数位数。


BTW, in the recent Python where .format() has superseded %, you could use

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

"{0:<15} = {2:6.{1}f}".format(id, i, val)

for the same task.

同样的任务。

Or, with field names for clarity:

或者,以字段名表示清晰:

"{id:<15} = {val:6.{i}f}".format(id=id, i=i, val=val)

If you are using Python 3.6+, you could simply use f-strings:

如果您使用的是Python 3.6+,可以使用f-string:

f"{id:<15} = {val:6.{i}f}"

#2


8  

I know this an old thread, but there is a much simpler way to do this:

我知道这是一条古老的线索,但有一种更简单的方法:

Try this:

试试这个:

def printStr(FloatNumber, Precision):
    return "%0.*f" % (Precision, FloatNumber)

#3


0  

This should work too

这应该工作

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

where i is the precision required.

我的精度要求。

#1


27  

tabStr += '%-15s = %6.*f\n' % (id, i, val)  

where i is the number of decimal places.

这里是小数位数。


BTW, in the recent Python where .format() has superseded %, you could use

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

"{0:<15} = {2:6.{1}f}".format(id, i, val)

for the same task.

同样的任务。

Or, with field names for clarity:

或者,以字段名表示清晰:

"{id:<15} = {val:6.{i}f}".format(id=id, i=i, val=val)

If you are using Python 3.6+, you could simply use f-strings:

如果您使用的是Python 3.6+,可以使用f-string:

f"{id:<15} = {val:6.{i}f}"

#2


8  

I know this an old thread, but there is a much simpler way to do this:

我知道这是一条古老的线索,但有一种更简单的方法:

Try this:

试试这个:

def printStr(FloatNumber, Precision):
    return "%0.*f" % (Precision, FloatNumber)

#3


0  

This should work too

这应该工作

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

where i is the precision required.

我的精度要求。