androidcurious androidcurious - 1 month ago 32
Android Question

Format EditText to currency with whole numbers

All-
I have a

TextWatcher
that formats an
EditText
to currency format:

private String current = "";
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(!s.toString().equals(current)){
editText$.removeTextChangedListener(this);

String cleanString = s.toString().replaceAll("[$,.]", "");

double parsed = Double.parseDouble(cleanString);
String formated = NumberFormat.getCurrencyInstance().format((parsed/100));

current = formated;
editText$.setText(formated);
editText$.setSelection(formated.length());

editText$.addTextChangedListener(this);
}
}


This works great, the problem is that my
EditText
only needs whole numbers so I do not the user to be able to enter cents. So instead of 0.01 than 0.12 than 1.23 than 12.34, I want 1 than 12 than 123 than 1,234. How can I get rid of the decimal point but keep the commas? Thank you.

Answer

If you don't mind removing the period and trailing zeroes, you could do this:

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

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!s.toString().equals(current)) {
                annualIncomeEntry.removeTextChangedListener(this);

                String cleanString = s.toString().replaceAll("[$,]", "");

                if (cleanString.length() > 0) {
                    double parsed = Double.parseDouble(cleanString);
                    NumberFormat formatter = NumberFormat.getCurrencyInstance();
                    formatter.setMaximumFractionDigits(0);
                    current = formatter.format(parsed);
                } else {
                    current = cleanString;
                }


                annualIncomeEntry.setText(current);
                annualIncomeEntry.setSelection(current.length());
                annualIncomeEntry.addTextChangedListener(this);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }

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

This will set the number formatter's maximum fraction digits to zero, removing all trailing zeroes and the period. I also removed the division by 100 so that all entered numbers are integers.

Also make sure that your EditText's inputType is "number" or this will crash if the user tries to enter a non-numeric character.