-2

the code is working successfully but my problem is decimals length is very long, i need to reduce decimals in tkinter. i hope you will help..

my problem is

enter image description here

import tkinter as tk

root = tk.Tk()
root.geometry('850x450')

var1 = tk.StringVar()
t1 = tk.Entry(root, textvariable=var1).grid(row=1,column=1)
var2 = tk.StringVar()
t2 = tk.Entry(root, textvariable=var2).grid(row=1,column=2)
result = tk.StringVar()
l = tk.Label(root, textvariable=result).grid(row=1,column=3)


def set_label(name, index, mode):
    if var1.get() == '' or var2.get() == '':
        pass
    else:
        result.set(float(var1.get()) * float(var2.get()))

var1.trace('w', set_label)
var2.trace('w', set_label)

root.mainloop()
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
  • 1
    Does this answer your question? [How to round a number to n decimal places in Python](https://stackoverflow.com/questions/38390950/how-to-round-a-number-to-n-decimal-places-in-python) (This duplicate even used tkinter!) – msanford Sep 13 '20 at 14:10
  • 2
    use round() ? . – bb1950328 Sep 13 '20 at 14:10

2 Answers2

1

Decimals and rounding is done with the '{number:.{digits}f}' syntax.

N = 3 # number of decimals that you want
def set_label(name, index, mode):
    if var1.get() == '' or var2.get() == '':
        pass
    else:
        res = float(var1.get()) * float(var2.get())
        result.set('{number:.{digits}f}'.format(number=res, digits=N))
runDOSrun
  • 10,359
  • 7
  • 47
  • 57
0

you can use round() like so:

>>> round(1.123456789, 2)
1.12
>>> round(1.123456789, 4)
1.1234
Hadrian
  • 917
  • 5
  • 10