如何在Python中将数字舍入到n个小数位

时间:2016-07-15 08:03:44

标签: python tkinter decimalformat decimal-point

我想,我在输入字段中输入的内容应自动舍入到n个小数点。

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)
        a= Tk.DoubleVar()
        self.entry = Tk.Entry(frPic, textvariable=a)
        a.set(round(self.entry.get(), 2))

        self.entry.grid(row=0)
if __name__ == '__main__':
    app = InterfaceApp(root)
    root.mainloop()

2 个答案:

答案 0 :(得分:1)

您未获得预期结果,因为当您在a.set(round(self.entry, 2))内运行initialize()时,self.entry.get()的值始终为0(创建后的默认值)

您需要将callback附加到按钮小部件上,按下后,您要查找的行为将被执行:

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

答案 1 :(得分:0)

我想你想要的不是舍入浮点值本身,你想要显示一个精度为n小数点的浮点值。试试这个:

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

注意:在您的代码中,您尝试围绕self.entry .i。即您尝试对Tk.Entry类型的实例进行舍入。您应该使用为您提供字符串的self.entry.get()

如果您不熟悉这种字符串格式,请使用here