如何对计算结果进行舍入?
How Do I Round A Calculation Result?
如何四舍五入我的回合计数计算结果,使其显示为不带小数点的整数?
这是我的部分代码。我要舍入的结果在底部:
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
在 python 中有一个名为 round
的函数。
x=round(3.141,2)
print(x)
这将四舍五入到小数点后两位。所以输出将是:
3.14
另一种方法是格式化字符串。如果您在用户界面中使用四舍五入的值,这可能会更好,但继续使用更准确的值 'under the hood'。它是这样工作的。
>>> n= 1.23456789
>>> "Rounded result is %.2f" % n
'Rounded result is 1.23'
或使用format
方法。这是更 Python3 的方式。
>>> "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,您应该使用 round() 方法。
a = 23234.85245
print(a) #result is 23234.85245
print(round(a)) #result is 23235.0
print(int(round(a))) #result is 23235
如何四舍五入我的回合计数计算结果,使其显示为不带小数点的整数?
这是我的部分代码。我要舍入的结果在底部:
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
在 python 中有一个名为 round
的函数。
x=round(3.141,2)
print(x)
这将四舍五入到小数点后两位。所以输出将是:
3.14
另一种方法是格式化字符串。如果您在用户界面中使用四舍五入的值,这可能会更好,但继续使用更准确的值 'under the hood'。它是这样工作的。
>>> n= 1.23456789
>>> "Rounded result is %.2f" % n
'Rounded result is 1.23'
或使用format
方法。这是更 Python3 的方式。
>>> "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,您应该使用 round() 方法。
a = 23234.85245
print(a) #result is 23234.85245
print(round(a)) #result is 23235.0
print(int(round(a))) #result is 23235