简体   繁体   中英

How to add 3 decimal places Currency formatting to edittext Using TextWatcher Android

I want to add 3 decimal places currency formatting to EditText using TextWatcher at the beginning, value is 0.000 and the number should change right to left

eg: if I pressed 1,2,3,4,5 in order value should appear as this 12.345

following code is worked only for 2 decimal places. Please anyone helps me how to change this code for 3 decimal places or another solution

 public class CurrencyTextWatcher  implements TextWatcher {
    boolean mEditing;
    Context context;


    public CurrencyTextWatcher() {
        mEditing = false;
    }

    public synchronized void afterTextChanged(Editable s) {

        if(!mEditing) {
            mEditing = true;
            String digits = s.toString().replaceAll("\\D", "");
             NumberFormat nf = NumberFormat.getCurrencyInstance();

            try{
                String formatted = nf.format(Double.parseDouble(digits)/100);
                s.replace(0, s.length(), formatted);
            } catch (NumberFormatException nfe) {
                s.clear();
            }
            mEditing = false;
        }
    }

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

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

}

Divide 1000 instead of 100 and also setMinimumFractionDigits for NumberFormat as 3.

public class CurrencyTextWatcher  implements TextWatcher {
    boolean mEditing;
    Context context;


    public CurrencyTextWatcher() {
        mEditing = false;
    }

    public synchronized void afterTextChanged(Editable s) {

        if(!mEditing) {
            mEditing = true;
            String digits = s.toString().replaceAll("\\D", "");
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            nf.setMinimumFractionDigits(3);

            try{
                String formatted = nf.format(Double.parseDouble(digits)/1000);
                s.replace(0, s.length(), formatted);
            } catch (NumberFormatException nfe) {
                s.clear();
            }
            mEditing = false;
        }
    }

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM