Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

python - How to specify floating point decimal precision from variable?

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
' % (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.

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

Any ideas how to accomplish this kind of functionality?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
tabStr += '%-15s = %6.*f
' % (id, i, val)  

where i is the number of decimal places.


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

"{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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...