Python 如何舍入计算结果?
如何舍入轮次计数计算的结果,使其显示为不带小数点的整数 这是我的部分代码。下面是我想讨论的结果:Python 如何舍入计算结果?,python,tkinter,rounding,Python,Tkinter,Rounding,如何舍入轮次计数计算的结果,使其显示为不带小数点的整数 这是我的部分代码。下面是我想讨论的结果: 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
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()
在python中有一个名为round的函数 这将四舍五入到小数点后两位。因此,输出将是:
3.14
另一种方法是格式化字符串。如果您在用户界面中使用四舍五入的值,这可能会更好,但请继续使用更精确的“引擎盖下”值。它是这样工作的
>>> n= 1.23456789
>>> "Rounded result is %.2f" % n
'Rounded result is 1.23'
或者使用格式化方法。这更像是蟒蛇的方式
>>> "Rounded result is {:.2f}".format(n)
'Rounded result is 1.2'
您可以在其中添加前导零或空格。第一个数字告诉您的结果总共有多少个字符,第二个数字告诉您使用了多少个小数
>>> "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'
基本上可以使用内置函数int将浮点数转换为整数
a = 2342.242345
print(a) #result is 2342.242345
print(int(a)) #result is 2342
这基本上会删除点后的所有数字,因此不会舍入或限定浮点值
要将类似于24524.9234234的值舍入为24525而不是24524,应使用舍入方法
a = 23234.85245
print(a) #result is 23234.85245
print(round(a)) #result is 23235.0
print(int(round(a))) #result is 23235
这就是我想做的。然而,我不知道在哪里或者如何将它添加到我的代码中。不管怎样,我已经找到了答案。而且它有效!很高兴听到这个消息,但ı不明白你不能理解的部分。似乎您对Tkinter库而不是数据类型有疑问。
a = 23234.85245
print(a) #result is 23234.85245
print(round(a)) #result is 23235.0
print(int(round(a))) #result is 23235