Even-though It's late. Intended for future visitors.

Fetures of the following codes

  1. Puts thousand separator in EditText as it's text changes.

  2. adds 0. Automatically when pressed period (.) At First.

  3. Ignores 0 input at Beginning.

Just copy the following Class named

NumberTextWatcherForThousand which implements TextWatcher

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.util.StringTokenizer;

/**
 * Created by skb on 12/14/2015.
 */
public class NumberTextWatcherForThousand implements TextWatcher {

    EditText editText;


    public NumberTextWatcherForThousand(EditText editText) {
        this.editText = editText;


    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        try
        {
            editText.removeTextChangedListener(this);
            String value = editText.getText().toString();


            if (value != null && !value.equals(""))
            {

                if(value.startsWith(".")){
                    editText.setText("0.");
                }
                if(value.startsWith("0") && !value.startsWith("0.")){
                    editText.setText("");

                }


                String str = editText.getText().toString().replaceAll(",", "");
                if (!value.equals(""))
                editText.setText(getDecimalFormattedString(str));
                editText.setSelection(editText.getText().toString().length());
            }
            editText.addTextChangedListener(this);
            return;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            editText.addTextChangedListener(this);
        }

    }

    public static String getDecimalFormattedString(String value)
    {
        StringTokenizer lst = new StringTokenizer(value, ".");
        String str1 = value;
        String str2 = "";
        if (lst.countTokens() > 1)
        {
            str1 = lst.nextToken();
            str2 = lst.nextToken();
        }
        String str3 = "";
        int i = 0;
        int j = -1 + str1.length();
        if (str1.charAt( -1 + str1.length()) == '.')
        {
            j--;
            str3 = ".";
        }
        for (int k = j;; k--)
        {
            if (k < 0)
            {
                if (str2.length() > 0)
                    str3 = str3 + "." + str2;
                return str3;
            }
            if (i == 3)
            {
                str3 = "," + str3;
                i = 0;
            }
            str3 = str1.charAt(k) + str3;
            i++;
        }

    }

    public static String trimCommaOfString(String string) {
//        String returnString;
        if(string.contains(",")){
            return string.replace(",","");}
        else {
            return string;
        }

    }
}

Use This Class on your EditText as follows

editText.addTextChangedListener(new NumberTextWatcherForThousand(editText));

To get the input as plain Double Text

Use the trimCommaOfString method of the same class like this

NumberTextWatcherForThousand.trimCommaOfString(editText.getText().toString())

Git

Answer from Shree Krishna on Stack Overflow
Top answer
1 of 16
62

Even-though It's late. Intended for future visitors.

Fetures of the following codes

  1. Puts thousand separator in EditText as it's text changes.

  2. adds 0. Automatically when pressed period (.) At First.

  3. Ignores 0 input at Beginning.

Just copy the following Class named

NumberTextWatcherForThousand which implements TextWatcher

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import java.util.StringTokenizer;

/**
 * Created by skb on 12/14/2015.
 */
public class NumberTextWatcherForThousand implements TextWatcher {

    EditText editText;


    public NumberTextWatcherForThousand(EditText editText) {
        this.editText = editText;


    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        try
        {
            editText.removeTextChangedListener(this);
            String value = editText.getText().toString();


            if (value != null && !value.equals(""))
            {

                if(value.startsWith(".")){
                    editText.setText("0.");
                }
                if(value.startsWith("0") && !value.startsWith("0.")){
                    editText.setText("");

                }


                String str = editText.getText().toString().replaceAll(",", "");
                if (!value.equals(""))
                editText.setText(getDecimalFormattedString(str));
                editText.setSelection(editText.getText().toString().length());
            }
            editText.addTextChangedListener(this);
            return;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            editText.addTextChangedListener(this);
        }

    }

    public static String getDecimalFormattedString(String value)
    {
        StringTokenizer lst = new StringTokenizer(value, ".");
        String str1 = value;
        String str2 = "";
        if (lst.countTokens() > 1)
        {
            str1 = lst.nextToken();
            str2 = lst.nextToken();
        }
        String str3 = "";
        int i = 0;
        int j = -1 + str1.length();
        if (str1.charAt( -1 + str1.length()) == '.')
        {
            j--;
            str3 = ".";
        }
        for (int k = j;; k--)
        {
            if (k < 0)
            {
                if (str2.length() > 0)
                    str3 = str3 + "." + str2;
                return str3;
            }
            if (i == 3)
            {
                str3 = "," + str3;
                i = 0;
            }
            str3 = str1.charAt(k) + str3;
            i++;
        }

    }

    public static String trimCommaOfString(String string) {
//        String returnString;
        if(string.contains(",")){
            return string.replace(",","");}
        else {
            return string;
        }

    }
}

Use This Class on your EditText as follows

editText.addTextChangedListener(new NumberTextWatcherForThousand(editText));

To get the input as plain Double Text

Use the trimCommaOfString method of the same class like this

NumberTextWatcherForThousand.trimCommaOfString(editText.getText().toString())

Git

2 of 16
57

You can use String.format() in a TextWatcher. The comma in the format specifier does the trick.

This does not work for floating point input. And be careful not to set an infinite loop with the TextWatcher.

public void afterTextChanged(Editable view) {
    String s = null;
    try {
        // The comma in the format specifier does the trick
        s = String.format("%,d", Long.parseLong(view.toString()));
    } catch (NumberFormatException e) {
    }
    // Set s back to the view after temporarily removing the text change listener
}
Top answer
1 of 1
6

I will not discuss if it's re-inventing some wheel, but comment on the two code versions given.

Recursive version

The loop

    do {
        number = number % 1000;
    } while (number > 999);

is nonsense. number % 1000 can never be > 999, so number = number % 1000; without the loop does exactly the same.

In the "loop", re-assigning a new value to the method call parameter number is considered bad style. You should introduce a new variable, e.g. int remainder = number % 1000;.

You can avoid the error-prone handling of the positive flag by utilising recursion as well:

if (number < 0) {
    return "-" + intToThousandSpacedStringOS(-number);
}

You declare your variables very early, and later change their values from an (often useless) initial value to something useful, e.g.

String t = "";

Better declare your variables in the exact same line where you know their value. Or at least, don't assign an initial value, then the compiler gives you an error message if in some execution path you forgot to assign a useful value.

To sum it up, my recursive version would read

public static String intToThousandSpacedStringOS(int number) {
    if (number < 0) {
        return "-" + intToThousandSpacedStringOS(-number);
    } else if (number > 999) {
        return intToThousandSpacedStringOS(number / 1000) + 
               String.format(" %03d", number % 1000); // note the space in the format string.
    } else {
        return String.format("%d", number);
    }
}

Iterative version

Reading and understanding this version is a challenge, and that's a red flag. Don't expect any fellow programmer (and your future self next month) to understand what a line like

r = t.substring(t.length() - 3 * i > 3 ? t.length() - 3 * (i + 1) : 0, t.length() - 3 * i) + " " + r;

does. I guess you cut a chunk out of the original decimal string and prepend that, together with a space, to the result string. Then, at least introduce two variables like

int chunkStart = t.length() - 3 * i > 3 ? t.length() - 3 * (i + 1) : 0;
int chunkEnd = t.length() - 3 * i;
r = t.substring(chunkStart, chunkEnd) + " " + r;

With the ternary-operator conditional, you probably want to avoid a negative chunkStart. I'd write

int chunkStart = Math.max(t.length() - 3 * (i + 1), 0);
int chunkEnd = t.length() - 3 * i;
r = t.substring(chunkStart, chunkEnd) + " " + r;

or

int chunkStart = t.length() - 3 * (i + 1);
if (chunkStart < 0) chunkStart = 0;
int chunkEnd = t.length() - 3 * i;
r = t.substring(chunkStart, chunkEnd) + " " + r;

You seem to love while loops. Typically, for loops are much more readable, as they combine all loop aspects in a single line - your while loop spreads its aspects over half of the method length:

  • The initial value is found in line 12: int i = 1;.
  • The condition is in line 20: while (t.length() > 3 * i) {.
  • The updating is in line 22: i++;.

The variable i that you use in the loop is only loosely related to the values you need inside the loop. You want to iterate a position inside the string backwards from the end, in 3-character steps. A straightforward loop would be e.g.

for (int chunkEnd = t.length() - 3; chunkEnd > 0; chunkEnd -= 3) {
    ...
}
Discussions

Unable to change number format in calculator and other apps. I use the comma to sperate thousands - Android Community
Skip to main content · Android Help · Sign in · Google Help · Help Center · Community · Android · Terms of Service · Submit feedback · Send feedback on More on support.google.com
🌐 support.google.com
March 17, 2023
java - How can I format a String number to have commas in android Edit Field - Stack Overflow
For what function I can use in android to display the number into different formats. For eg: If I enter 1000 then it should display like this 1,000. If I enter 10000 then it should display like t... More on stackoverflow.com
🌐 stackoverflow.com
November 5, 2013
thousands separator .
Hi, how can i format thousands separator . not , ?? example= 1000000 with format 1.000.000 in my region , is decimal. or 1000000.15 with format 1.000.000,15 Thanks!. More on b4x.com
🌐 b4x.com
0
0
August 28, 2019
Decimal separator android 10
In the rest of the world, at least in Europe, we use dots and commas the other way around in math. As the other person said, check if your phone language is set to American English, if not then I have no idea. Try live chatting or emailing OnePlus support. And I don't see what's wrong with Google's answer. More on reddit.com
🌐 r/AndroidQuestions
8
24
May 18, 2020
🌐
GitHub
github.com › NaturalizerINA › AndroidNumberSeparator
GitHub - NaturalizerINA/AndroidNumberSeparator: Number separator library for android · GitHub
The Android Number Separator is the lightweight library for separate number with coma in android or dot or dynamically by your locale device.
Starred by 12 users
Forked by 3 users
Languages   Java
🌐
GitHub
github.com › shreekrishnaban › NumberTextWatcherForThousand
GitHub - shreekrishnaban/NumberTextWatcherForThousand: This class is used For thousand seperator to the android EditText while taking currency input , This seperats the editText input with comma while user is entering the value
This class is used For thousand seperator to the android EditText while taking currency input , This seperats the editText input with comma while user is entering the value - shreekrishnaban/NumberTextWatcherForThousand
Starred by 22 users
Forked by 9 users
🌐
Iut-fbleau
iut-fbleau.fr › docs › android › reference › android › icu › text › DecimalFormat.html
DecimalFormat - Android SDK | Android Developers
It commonly used for thousands, but in some locales it separates ten-thousands. The grouping size is the number of digits between the grouping separators, such as 3 for "100,000,000" or 4 for "1 0000 0000". There are actually two different grouping sizes: One used for the least significant integer digits, the primary grouping size, and one used for all others, the secondary grouping size.
🌐
Codeplayon
codeplayon.com › home › android number format thousands separator
android number format thousands separator Archives – Codeplayon
November 21, 2019 - Posts Tagged "android number format thousands separator" Android developmentAndroid tutorial · Parmit Singh · 1.9k · Hii Developer in this Article I am sharing Android Number formatting and Convert String to Integer in Android. Convert String... "Get all latest content delivered straight to your inbox."
Find elsewhere
🌐
B4X
b4x.com › home › forums › b4a - android › android questions
Android Question thousands separator
August 28, 2019 - This solution from OliverA was perfect for an expert as UDG https://www.b4x.com/android/forum/threads/solved-setting-a-decimal-separator.105981/#post-663491 · Note that my "Expert" badge is just for the number of post...
🌐
Reddit
reddit.com › r/androidquestions › decimal separator android 10
r/AndroidQuestions on Reddit: Decimal separator android 10
May 18, 2020 -

Where I'm from, we use a comma as a decimal separator. For instance, 0,3 /0,5 / 3,84 / 2.656,74

Ever since I upgraded to android 10, my OnePlus 6t displays both the thousands separator as well as the decimal separator as a dot. Here's an example from my calculator. It's difficult to see if this number actually is 17.500,250 or 17.500.250.

It's not just an issue in my calculator. If I ask the Google assistant how much 500 lbs is in kilogrammes, it tells me it's 226 thousand kilogrammes.

Anyone has a solution? Thanks in advance!

🌐
GitHub
google-developer-training.github.io › android-developer-advanced-course-practicals › unit-3-make-your-apps-accessible › lesson-5-localization › 5-2-p-using-the-locale-to-format-information › 5-2-p-using-the-locale-to-format-information.html
5.2: Using the locale to format information · GitBook
The date is formatted in each specific language as shown in the figure. Numbers appear with different punctuation in different locales. In U.S. English, the thousands separator is a comma, whereas in France, the thousands separator is a space, and in Spain the thousands separator is a period.
🌐
Android Developers
developer.android.com › api reference › numberformat
NumberFormat | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Worldbestlearningcenter
worldbestlearningcenter.com › tips › Android-format-number.htm
Loading...
August 13, 2014 - Programming tutorials with exercises solutions questions answers tips of C, C++, Java, VB, VBA, C#.
🌐
YouTube
youtube.com › watch
input type number with Comma in Android | Decimal separator comma in EditText in Soft Keyboard - YouTube
Need Help or Code Support? Feel Free To Contact Us Here www.aaviskar.com/support.phpThis video focuses for input type number with Comma in Android and how to...
Published   October 5, 2020
🌐
B4X
b4x.com › home › forums › b4a - android › android questions
Android Question Thousands separator while typing
February 5, 2020 - BTW: 1 - first time I tried with B4J and SelectionStart is read only on it; 2 - I think it is better to have two global variables (process globals) in which to set which are the valid signs as a separator of thousands and decimals. ... It does not work. Click to expand... You misunderstood what this code does. The keyboard input type should be number or decimal.
🌐
GitHub
gist.github.com › momvart › 5e756f227ff3a813b5870260453fdb73
A VisualTransformation for inserting thousand-separator commas in TextFields inputting numbers. It also has support for fraction parts and can put limit on the number of fraction digits. #android #compose · GitHub
A VisualTransformation for inserting thousand-separator commas in TextFields inputting numbers. It also has support for fraction parts and can put limit on the number of fraction digits. #android #compose - ThousandSeparatorVisualTransformation.kt
🌐
IIT Kanpur
iitk.ac.in › esc101 › 05Aug › tutorial › java › data › decimalFormat.html
Formatting Numbers with Custom Formats
You can use the DecimalFormat class to format decimal numbers into strings. This class allows you to control the display of leading and trailing zeros, prefixes and suffixes, grouping (thousands) separators, and the decimal separator. If you want to change formatting symbols, such as the decimal ...