1

I need the input to adapt to the final number as they enter the digits, without actually entering the decimal point. The best way to explain this is with an example:

Suppose the user starts off with an EditText field which contains this:

.

The user wants to enter 1234.01 into the field (i.e. the digits 0,1,2,3,4). Then he/she starts by entering 1, and the field should look like this:

0.01

Then:

0.12

Next:

1.23

Next:

12.34

Next:

123.40

Finally:

1234.01

So as you may notice, the decimal places itself accordingly as the numbers are inputted. Is it possible to do this as the numbers are being entered? Thanks.

Shekhar Jadhav
  • 1,035
  • 9
  • 20
  • Can you kindly clarify further what you are looking for, and to post what you have tried to do. – coder Sep 22 '17 at 06:23
  • 1
    Follow this https://stackoverflow.com/questions/6636444/edittext-showing-numbers-with-2-decimals-at-all-times – Ankita Sep 22 '17 at 06:27
  • When I enter text in EditText then it should appears like I have explained in example. – Shekhar Jadhav Sep 22 '17 at 06:28
  • https://stackoverflow.com/questions/12830284/android-adding-decimal-point-to-edittext-field-and-make-it-move-with-input – Ankita Sep 22 '17 at 06:37

1 Answers1

0

You can achieve this with TextWatcher .

In your xml file, create a EditText like :

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/edt"
    android:inputType="numberDecimal"
    android:textDirection="anyRtl"
    android:gravity="right"/>

Now, In your Java file do something like this with your editText :

final EditText editText = (EditText) findViewById(R.id.edt);
    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editText == null) return;
            String inputString = editable.toString();
            editText.removeTextChangedListener(this);
            String cleanString = inputString.toString().replaceAll("[.]", "");
            BigDecimal bigDecimal = new BigDecimal(cleanString).setScale(2, BigDecimal.ROUND_FLOOR).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR);
            String  converted = NumberFormat.getNumberInstance().format(bigDecimal).replaceAll("[,]","");
            editText.setText(converted);
            editText.setSelection(converted.length());
            editText.addTextChangedListener(this);
        }
    });
Anurag
  • 1,162
  • 6
  • 20