How to specify floating point decimal precision from variable?

本秂侑毒 提交于 2019-11-30 18:32:39
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

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

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)

This should work too

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

where i is the precision required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!