I want to add or insert thousands commas in between digits of a number as long as I input digits like some calculators (see the image). For example, when I begin inputting the digits 793, the code inserts automatically a thousands comma if I input the forth digit say for example 5, hense the number looks like 7,935 and so forth. I have no idea, it seems difficult for me. You can show me with a variable, a text edit or anything else, and any help even small would be appreciated.
Asked
Active
Viewed 80 times
0
-
https://stackoverflow.com/questions/1823058/how-to-print-a-number-using-commas-as-thousands-separators – Chris Charley Aug 12 '23 at 19:36
-
Its hard to answer without seeing how values are entered. Do you have a minimal example? If digits are being entered, does that mean you are accumulating a string value? If so, you could convert that to an integer then use regular string formatting. – tdelaney Aug 12 '23 at 19:38
-
Do you mean when you're typing the input? – Arifa Chan Aug 15 '23 at 03:14
-
Yes, while I'm inputting or writing the digits of a number, just like in some calculators. – magid00 Aug 15 '23 at 07:38
3 Answers
0
You can use Python's built-in string formatting to achieve this. Here's how you can insert thousands commas into a number.
def format_number_with_commas(number):
return "{:,}".format(number)
# Test
n = 1234567890
formatted_number = format_number_with_commas(n)
print(formatted_number) # Output: 1,234,567,890
When you run the code above, it will print 1,234,567,890. The format() function with the :, format specifier adds commas as thousands separators.

Sukumar
- 69
- 9
0
Basically you will have to somehow set an event trigger whenever there is a change in text block and upon receiving that trigger, update incoming text with the ones with added commas.
General python function that does the job would be something like this
def add_commas_to_num(curr_text):
curr_text = curr_text.replace(',', '')
output = ''
for dig_no, letter in enumerate(curr_text[::-1]):
output = letter + output
if (dig_no+1)%3==0:
output = ',' + output
return output.strip(',')
edit : The two answers above are a lot better as they use python's inherent functionality. If you need to put it into function, it might look something like this
def add_commas_to_num(curr_text : str = '0'):
curr_text = curr_text.strip().replace(',', '')
return "{:,}".format(int(curr_text))

Bubble3D
- 14
- 3
-
You understood what I meant. Your code is very nice but, the commas appear when I enter the third digit. I want it to insert commas "after" I enter the forth digit not "before". In short, commas don't appear until l enter the forth digit. I've tried some modifications to your code but useless. Can you help, please? – magid00 Aug 13 '23 at 10:40
-