0

I am in need of a currency type EditText and using this currently: https://github.com/faranjit/currency_edittext

The problem with this is, you have to type decimal fields too.

Wrong:

If you want to input $1 you need to press 1-0-0.

If you want to type $1.5 you need to press 1-5-0.

However what I want to achieve is:

If you want to input $1 , you just press 1

If you want to input $1.5, you press 1-DOT-5

How should I modify this code to work like this?

yigitserin
  • 573
  • 2
  • 6
  • 24

2 Answers2

0

This works for me Try doing it

 editText.addTextChangedListener(new TextWatcher() {
        private String current = "";

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

        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!s.toString().equals(current)) {
                editText.removeTextChangedListener(this);

                Locale local = new Locale("id", "id");
                String replaceable = String.format("[Rp,.\\s]",
                        NumberFormat.getCurrencyInstance().getCurrency()
                                .getSymbol(local));
                String cleanString = s.toString().replaceAll(replaceable,
                        "");

                double parsed;
                try {
                    parsed = Double.parseDouble(cleanString);
                } catch (NumberFormatException e) {
                    parsed = 0.00;
                }

                NumberFormat formatter = NumberFormat
                        .getCurrencyInstance(local);
                formatter.setMaximumFractionDigits(0);
                formatter.setParseIntegerOnly(true);
                String formatted = formatter.format((parsed));

                String replace = String.format("[Rp\\s]",
                        NumberFormat.getCurrencyInstance().getCurrency()
                                .getSymbol(local));
                String clean = formatted.replaceAll(replace, "");

                current = formatted;
                editText.setText(clean);
                editText.setSelection(clean.length());
                editText.addTextChangedListener(this);
            }
        }
    });
pravin maske
  • 72
  • 1
  • 13
0

Set input type number.

To do so replace android:inputType="numberDecimal" with android:inputType="number".

buzzingsilently
  • 1,546
  • 3
  • 12
  • 18