Search code examples
javaandroidandroid-edittextmasking

EditText decimal mask for android


I'm working in an Android application and i want to create a decimal mask for editText in android. I want a mask like a maskMoney jQuery plugin. But in some cases my number will have 2 decimal places, 3 decimal places or will be a integer. I want do something like this:

  • When the EditText is created, come with a default value: 00.01
  • If user press the number 2, the result should be: 00.12
  • If user press the number 3, the result should be: 01.23
  • If user press the number 4, the result should be: 12.34
  • If user press the number 5, the result should be: 123.45
  • If user press the number 6, the result should be: 1,234.56

What's the best way to do that?


Solution

  • I resolved with this:

    public static TextWatcher amount(final EditText editText, final String metric) {
        return new TextWatcher() {
            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();
    
                    if (count != 0) {
                        String substr = cleanString.substring(cleanString.length() - 2);
    
                        if (substr.contains(".") || substr.contains(",")) {
                            cleanString += "0";
                        }
                    }
    
                    cleanString = cleanString.replaceAll("[,.]", "");
    
                    double parsed = Double.parseDouble(cleanString);
                    DecimalFormat df = new DecimalFormat("0.00");
                    String formatted = df.format((parsed / 100));
    
                    current = formatted;
                    editText.setText(formatted);
                    editText.setSelection(formatted.length());
    
                    editText.addTextChangedListener(this);
                }
            }
    
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
            public void afterTextChanged(Editable s) {}
        };
    }