How to format a numeric Entry with commas (,) in Python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • IRAQSTONE
    New Member
    • Mar 2020
    • 2

    How to format a numeric Entry with commas (,) in Python

    Am using Python 3.7 when a user enters a number, he expects to see the figure displayed in the entry field with commas.

    eg 3755125.70 to be displayed as 3,755,125.70. Is it possible?
  • SioSio
    Contributor
    • Dec 2019
    • 272

    #2
    Code:
    f = float(input())
    print('{:,}'.format(f))

    Comment

    • IRAQSTONE
      New Member
      • Mar 2020
      • 2

      #3
      Please is it possible to be part of the Entry options python?
      eg FloatNumber=Ent ry(textvariable = f, ('{:,}'.format( f))

      thanks

      Comment

      • Ishan Shah
        New Member
        • Jan 2020
        • 47

        #4
        For your solution, the following code will work :

        Code:
        from tkinter import *
        import locale
        root = Tk()
        
        FloatNumber = float(input('Enter no : '))
        b = Entry(root, textvariable = FloatNumber, justify = RIGHT).pack()
        
        def getOutput(*events):
            x = FloatNumber.get()
            y = x.replace(",",'')
            z = float(y)
            print(z)
            try:
                asd = format(z,',')
                print(asd)
            except:
                print("b")
            #Overwrite the Entrybox content using the widget's own methods
            b.delete(0, END)
            b.insert(0, asd)
        
        FloatNumber.trace('w',getOutput)
        root.mainloop()

        Comment

        • hussainmujtaba
          New Member
          • Apr 2020
          • 13

          #5
          import locale
          >>> locale.setlocal e(locale.LC_ALL , 'en_US')
          'en_US'
          >>> locale.format(" %d", 3755125, grouping=True)
          '3,755,125'

          Comment

          • lewish95
            New Member
            • Mar 2020
            • 33

            #6
            In this method, the part after the colon is the format specifier. The comma is the separator character you want,
            This is equivalent of using format(num, ",d") for older versions of python.
            we can use my_string = '{:,. 2f}'. format(my_numbe r) to convert float value into commas as thousands separators.

            Comment

            Working...