How to round a number to n decimal places?

后端 未结 2 957
生来不讨喜
生来不讨喜 2021-01-29 13:36

I want, what I enter in the entry field should be automatic rounded to n decimal points.

import Tkinter as Tk

root = Tk.Tk()

class InterfaceApp():
    def __in         


        
相关标签:
2条回答
  • 2021-01-29 14:27

    You do not get the expected result because when you run a.set(round(self.entry, 2)) inside initialize() , the value of self.entry.get() is always 0 (the default value after creation)

    You rather need to attach a callback to a button widget on which, after pressing, the behavior you are looking for will be executed:

    import Tkinter as Tk
    
    root = Tk.Tk()
    
    class InterfaceApp():
    
        def __init__(self,parent):
            self.parent = parent
            root.title("P")
            self.initialize()
    
        def initialize(self):
            frPic = Tk.Frame(bg='', colormap='new')
            frPic.grid(row=0, column=0)
            self.a = Tk.DoubleVar()
            self.entry = Tk.Entry(frPic, textvariable=self.a)
            self.entry.insert(Tk.INSERT,0)
            self.entry.grid(row=0, column=0)
            # Add a button widget with a callback
            self.button = Tk.Button(frPic, text='Press', command=self.round_n_decimal)
            self.button.grid(row=1, column=0)
        # Callback    
        def round_n_decimal(self):      
           self.a.set(round(float(self.entry.get()), 2))
    
    if __name__ == '__main__':
        app = InterfaceApp(root)
        root.mainloop()
    
    0 讨论(0)
  • 2021-01-29 14:31

    I suppose what you want is not to round the float value itself, you want to show a float value with a precision of n decimal points. Try this:

    >>> n = 2
    >>> '{:.{}f}'.format( 3.1415926535, n )
    '3.14'
    >>> n = 3
    >>> '{:.{}f}'.format( 3.1415926535, n )
    '3.142'
    

    Note: in your code you try to round self.entry .i. e. you try to round an instance of type Tk.Entry. You should use self.entry.get() which supplies you with a string.

    If you are not familiar with this kind of string formatting I use look here.

    0 讨论(0)
提交回复
热议问题