【问题标题】:How dynamically change the precision of value using {:10.4f}'.format( [Python]如何使用 {:10.4f}'.format( [Python] 动态更改值的精度
【发布时间】:2021-08-14 22:26:33
【问题描述】:

我有一个变量“n”,其中包含需要为值显示的多个数字。如何将“n”传递给'{: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)

【问题讨论】:

    标签: python python-3.x uncertainty


    【解决方案1】:

    你可以试试这个:

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

    【讨论】:

      【解决方案2】:
      result='{0:10.{1}f}'.format(result, n)
      

      【讨论】:

      • 感谢您的建议。不幸的是,对于我需要实现它的代码(在示例中它要复杂得多),它给了我一个错误:无法从自动字段编号切换到手动字段规范。但是 bb1 的建议奏效了。
      猜你喜欢
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2016-06-12
      相关资源
      最近更新 更多