【问题标题】:How to round to 2 decimals in python tkinter如何在 python tkinter 中舍入到 2 位小数
【发布时间】:2021-09-20 12:37:08
【问题描述】:

我正在编写一个计算百分比的小程序,但我找不到将结果四舍五入到小数点后两位的方法。

  • 有一个输入数字的字段
  • 还有另一个字段用于输入第二个数字(或通过单击按钮增加)
  • 有一个字段显示百分比

我认为我需要在函数中使用"{:.2f}" 之类的东西,但我不知道具体在哪里

这是我认为我必须输入命令的代码部分:

# 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()

一切都已创建(按钮、标签等),并且可以正常工作。

我已经附上了程序的 GUI。谢谢。

【问题讨论】:

  • 请考虑分享您的所有代码
  • 使用rate.set("{:.2f}".format((vaccint / popint) * 100))
  • 成功了!谢谢亨利!
  • 如果你有 Python 3.6+ 并且想使用f strings(这是首选):rate.set(f'{(vaccint / popint) * 100: .2f}')

标签: python python-3.x tkinter


【解决方案1】:

一旦你得到百分比,当你这样做时:

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

我只是取了一个任意浮点值并执行:

round(75.678780,2)

输出: 75.68

【讨论】:

    猜你喜欢
    • 2022-12-20
    • 2014-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多