How to specify floating point decimal precision from variable?
Asked Answered
S

4

25

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.

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

Any ideas how to accomplish this kind of functionality?

Sennight answered 6/4, 2011 at 22:28 Comment(0)
C
47
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}"
Cornett answered 6/4, 2011 at 22:36 Comment(0)
A
15

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)
Amphithecium answered 3/9, 2013 at 19:40 Comment(0)
C
0

This should work too

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

where i is the precision required.

Cornelius answered 7/4, 2011 at 1:8 Comment(0)
T
0

Tested in Python 3.8 and 3.9:

>>> val = 1.123456789
>>> decimals = 3
>>> f"{val:0.{decimals}f}"
'1.123'
Thornberry answered 7/8, 2023 at 8:56 Comment(1)
This solution has already been given.Judijudicable

© 2022 - 2024 — McMap. All rights reserved.