I would like to know how to convert a number into a formatted "number" format that has commas. I am on Mac OSX. An expression is inputted and evaluated within an entry widget and then output into a label widget with the following function:
def evaluate(self, event):
data = self.e.get()
self.ans.configure(text = "Answer: " + str(eval(data)))
I need the resulting output to be in a "number" format. For example, if the output is "34523000", I want it to say "34,523,000".
Use the locale
module.
If you are on Ubuntu, you can check the list of your locales by typing locale -a
on your Terminal. On my machine, I see a long list from which I choose, for example, 'en_US.utf8
'.
Once you have done that, go back to your function and do these changes:
import locale
# ...
# ...
# It is better to run this outside your function:
locale.setlocale(locale.LC_ALL, 'en_US.utf8')
# ...
# ...
def evaluate(self, event):
entry_data = self.e.get()
data = locale.format("%d", entry_data, grouping=True)
# ...
# ...
Here is a quick demo with the example data you provided:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US.utf8')
'en_US.utf8'
>>> locale.format("%d", 34523000, grouping=True)
'34,523,000'