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

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

本文介绍了如何从变量中指定浮点小数精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下重复的简单代码重复了几次,希望为其提供功能:

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)

我希望能够调用此函数:def printStr(precision)
它执行上面的代码,并返回带有valprecision小数点的tabStr.

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.

例如:printStr(3)
将在tabStr中为val返回63.457.

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

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

Any ideas how to accomplish this kind of functionality?

推荐答案

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

其中i是小数位数.

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

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

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

用于同一任务.

或者,为了清楚起见,使用字段名称:

Or, with field names for clarity:

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

如果您使用的是Python 3.6+,则可以简单地使用 f字符串:

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

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

这篇关于如何从变量中指定浮点小数精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:23