Skip to content Skip to sidebar Skip to footer

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' va

Solution 1:

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

Solution 2:

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

Try this:

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

Solution 3:

This should work too

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

where i is the precision required.

Post a Comment for "How To Specify Floating Point Decimal Precision From Variable?"