How to round a number to n decimal places?

后端 未结 2 956
生来不讨喜
生来不讨喜 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: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.

提交回复
热议问题