pythonpython-3.xuncertainty

How dynamically change the precision of value using {:10.4f}'.format( [Python]


I have a variable "n" that contains a number of digits that need to be displayed for the value. How to pass the "n" to '{:10.nf}'.format()?

import uncertainties
from uncertainties.umath import *

val_err = uncertainties.ufloat(5, 0.01)
result = val_err*2
n=3  #precision value
result='{:10.nf}'.format(result)
print(result)

Solution

  • You can try this:

    r = 3.1415926
    n = 5
    
    template = f"{{:10.{n}f}}"
    result = template.format(r)
    print(result)