简体   繁体   English

python tkinter 如何四舍五入到两位小数

[英]How to round to 2 decimals in python tkinter

I'm making a small program that calculates a percentage, but I can't find the way to round the result to 2 decimals.我正在制作一个计算百分比的小程序,但我找不到将结果四舍五入到两位小数的方法。

  • There is a field for inputting a number有一个输入数字的字段
  • There is another field for inputting a second number (or increase it by clicking the button)还有另一个字段用于输入第二个数字(或通过单击按钮增加它)
  • There is a field that shows the percent有一个字段显示百分比

I believe I need to use something like "{:.2f}" in the function, but I don't know where exactly我相信我需要在 function 中使用类似"{:.2f}"的东西,但我不知道具体在哪里

This is the part of my code where I reckon I have to put the command:这是我的代码的一部分,我认为我必须在其中放置命令:

# Defining a function that takes any arguments and calulcates the proportion of the population and the vaccinated
def calculate(*args):
    try:
        popint = float(pop.get())
        vaccint = float(vacc.get())
        rate.set((vaccint / popint) * 100)
    except ValueError:
        pass  # Ignore for now

# Defining a function that increases by 1 the number of vaccinated
def addvacc(*args):
    try:
        vaccadd = int(vacc.get())
        vacc.set(vaccadd + 1)
        calculate()
    except ValueError:
        pass # Ignore for now

# Creating a window with title
root = Tk()

Everything is created already (buttons, labels, etc.), and it works.一切都已创建(按钮、标签等),并且可以正常工作。

图像

I've attached the GUI of the program.我附上了程序的图形用户界面。 Thank you.谢谢。

Once you get the percentage, and when you do this:一旦你得到百分比,当你这样做时:

round(<your percentage value>,2)  #syntax: round(Value, digits to be rounded off to)

I just took an arbitrary float value and executed:我只是取了一个任意的浮点值并执行了:

round(75.678780,2)

Output: 75.68 Output: 75.68

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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