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

Time:11-27

So I have the following code

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

read_log is the function and it is getting the machine_busy_value. it is currently returning a floating number but I would like it to return the value in 2 decimal places. How can I go about that? Any type of suggestion would be appreciated. I am using python 2.7 if that helps

CodePudding user response:

You might consider using format()

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

That's python 2.7 (which doesn't have f-strings). There are plenty of questions like this already out there

If you're on python 3.7, then you can just end your read_log call in the string with the :.2f to format it.

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

CodePudding user response:

Python has a round function which you can call as such: round(The number you want to round, The number of decimal points)

So you should save your floating number, round it then print it.

  • Related