Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android EditText AddTextChangeListener Currency Format

Through SO I put together the following EditText addTextChangedListener event handler, it works fine except for a little improvement that I need. When I type, it populates the digits from right to left. I would rather it populates from left to right. Right now if I enter 50 it formats as $0.50, when I enter 50 I want it to format as $50.00

Below is the xml declaration and the Java code, please can someone point me to what I need to change to get the desired result.

enter image description here

XML declaration

    <EditText
        android:id="@+id/valueEditText"
        android:layout_row="1"
        android:hint="@string/hint_value_to_add"
        android:imeOptions="actionNext"
        android:inputType="numberDecimal"
        style="@style/EnrollEditViewStyle" />
    <requestFocus />

Java Code

      inputValue = (EditText) findViewById(R.id.valueEditText);
        inputValue.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) {
                // TODO Auto-generated method stub

            }

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

                    String replaceable = String.format("[%s,.\\s]", NumberFormat.getCurrencyInstance().getCurrency().getSymbol());
                    String cleanString = s.toString().replaceAll(replaceable, "");

                    double parsed;
                    try {
                        parsed = Double.parseDouble(cleanString);
                    } catch (NumberFormatException e) {
                        parsed = 0.00;
                    }
                    String formatted = NumberFormat.getCurrencyInstance().format((parsed/100));

                    current = formatted;
                    inputValue.setText(formatted);
                    inputValue.setSelection(formatted.length());
                    inputValue.addTextChangedListener(this);
                }
            }
        });
like image 201
Val Okafor Avatar asked Nov 19 '14 21:11

Val Okafor


2 Answers

Per this SO question Format EditText to currency with whole numbers I added setMaximumFractionDigits to 0 like so

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

        String replaceable = String.format("[%s,.\\s]",   NumberFormat.getCurrencyInstance().getCurrency().getSymbol());
        String cleanString = s.toString().replaceAll(replaceable, "");

        double parsed;
        try {
            parsed = Double.parseDouble(cleanString);
        } catch (NumberFormatException e) {
            parsed = 0.00;
        }
        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        formatter.setMaximumFractionDigits(0);
        String formatted = formatter.format((parsed));

        current = formatted;
        inputValue.setText(formatted);
        inputValue.setSelection(formatted.length());
        inputValue.addTextChangedListener(this);
    }
like image 120
Val Okafor Avatar answered Nov 08 '22 14:11

Val Okafor


Kotlin version

var current = ""

editText.addTextChangedListener(object: TextWatcher {
    override fun afterTextChanged(s: Editable?) {}
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        val stringText = s.toString()

        if(stringText != current) {
            editText.removeTextChangedListener(this)

            val locale: Locale = Locale.UK
            val currency = Currency.getInstance(locale)
            val cleanString = stringText.replace("[${currency.symbol},.]".toRegex(), "")
            val parsed = cleanString.toDouble()
            val formatted = NumberFormat.getCurrencyInstance(locale).format(parsed / 100)

            current = formatted
            editText.setText(formatted)
            editText.setSelection(formatted.length)
            editText.addTextChangedListener(this)
        }
    }
})
like image 41
Adriatik Gashi Avatar answered Nov 08 '22 13:11

Adriatik Gashi