How to round to 2 decimals in python tkinter

  python, python-3.x, 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 where to put a number,
There is another field where to put 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

This is 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, ecc) and it works.

Image

I’ve attached the GUI of the program.
Thank you

Source: Python-3x Questions

LEAVE A COMMENT