如何直接从打印行 python 函数中将浮点数四舍五入到小数点后一位

How to round off a floating number to one decimal place from the print line python function directly

所以我有以下代码

for x in range(10):
  
    print(f'Machine Busy Val     : {read_log ("Machine_busy_value")}')

read_log 是函数,它正在获取 machine_busy_value。它目前 return 是一个浮点数,但我希望它 return 小数点后两位的值。我该怎么做?任何类型的建议将不胜感激。如果有帮助,我正在使用 python 2.7

Python 有一个圆形函数,您可以这样调用: round(要四舍五入的数字,小数点后的位数)

所以你应该保存你的浮点数,四舍五入然后打印它。

您可以考虑使用 format()

print ("{val:.1f}".format(val=read_log("Machine_busy_value") ))

那是 python 2.7(没有 f 弦)。已经有很多 questions like this

如果您使用的是 python 3.7,那么您只需在字符串中使用 :.2f 结束 read_log 调用即可对其进行格式化。

f'Machine Busy Val     : {read_log ("Machine_busy_value"):.1f}'