简体   繁体   中英

How Do I Round A Calculation Result?

How do I round the outcome of my Turn Count calculation so it will show as a whole number with no decimal points?

Here is part of my code. The outcome I wish to round is at the bottom:

from tkinter import *
import os
os.system('clear')

Button(root, text='Calculate', command=turn_count).pack(pady=30)

myLabel = Label(root, text='Turn Count', bg='#ffc773')
myLabel.pack(pady=10)

count_label = Label(root, width=20) #this is where the calculation appears
count_label.pack()

root.mainloop()

This is the program I wrote

In python there is a function called round .

x=round(3.141,2)
print(x)

This will round to only two decimal places. So output will be:

3.14

Another approach would be format string. This can be better if you use rounded value in user interface, but keep on using more accurate value 'under the hood'. It work like this.


>>> n= 1.23456789

>>> "Rounded result is %.2f" % n
'Rounded result is 1.23'

Or using format method. This is more Python3-way.

>>> "Rounded result is {:.2f}".format(n)
'Rounded result is 1.2'

There you can add leading zeros or whitespace. First number tells how many chars in total your result is, second how many decimals are used.

>>> "Rounded result is {:7.4f}".format(2.56789)
'Rounded result is   2.568'
>>> "Rounded result is {:07.4f}".format(2.56789)
'Rounded result is 002.568'
>>> "Rounded result is {:.0f}".format(2.56789)
'Rounded result is 3'

You can basically use the built in function int() to convert floating numbers to integers.

a = 2342.242345

print(a)        #result is 2342.242345
print(int(a))   #result is 2342

This basically removes all numbers after the dot, so not rounding or flooring the float value.

For rounding a value similar to 24524.9234234 to 24525 instead of 24524, you should use round() method.

a = 23234.85245

print(a)             #result is 23234.85245
print(round(a))      #result is 23235.0
print(int(round(a))) #result is 23235

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM