How to Automatically add thousand separators for every number in a string?

494 Views Asked by At

How can i create a thousand separator for every number which is in my string?

So for example this string:

string = "123456,78+1234"

should be displayed as:

TextView = "123.456,78+1.234"

And the string should be editable, so the thousand separator should adapt when i remove or add a digit.

I have already read all the posts I could find about it, but I could never find an up-to-date working answer. So I would be really grateful for your help!

1

There are 1 best solutions below

0
On

Your question contains two sub-questions:

A. You want to add thousand separators to a string which contains a group of numbers.

B. You want it to change.

And the answers are:

A: In your example there's , as a delimiter, so you need to split the string using this delimiter to an array of strings.

Then iterate over them and have your dots added to every 3nth index of their characters; you can also use String.format("%,d", substr.toLong()).

Lastly, append all of the strings back together with , as the separator.

B: This one can be done in different ways. You may store the original string somewhere and observe it, so when it changes it goes to the function which does A, and use the function result the way you like (which I suppose is to be set in a TextView).