Search code examples
androidandroid-edittextformattextwatcherandroid-textwatcher

Android reverse money input with fixed decimal


I want to create an Eddittext to type in currency values with 2 decimals from left to right. If there´s no value it shows 0.00, and as the user types the text should change acording to these rules: Input rules

I´ve tried getting it done using TextWatcher like in a similar question but I couldnt get it done as it kept calling TextWatcher after updating the text.


Solution

  • I finally got it working just as I wanted using a TextWatcher with this code, hope it helps someone:

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if ((count - before) > 0) {
                    String text = s.toString().replace(',', '.');
                    text = text.replace("..", ".");
                    if (text.equals(".")) {
                        text = "0,00";
                        amount_field.setText(text);
                        amount_field.setSelection(2);
    
                    } else {
                        int counter = 0;
                        for (int i = 0; i < text.length(); i++) {
                            if (text.charAt(i) == '.') {
                                counter++;
                                if (counter > 1) {
                                    break;
                                }
                            }
                        }
    
                        if (counter > 1) {
                            StringBuilder sb = new StringBuilder(text);
                            sb.deleteCharAt(start);
                            amount_field.setText(sb.toString().replace('.', ','));
                            amount_field.setSelection(start);
    
                        } else {
                            Float value = Float.valueOf(text);
                            String result = String.format("%.2f", value);
                            amount_field.setText(result.replace('.', ','));
                            if (start != result.length()) {
                                amount_field.setSelection(start + 1);
                            } else {
                                amount_field.setSelection(start);
                            }
                        }
                    }
                }
            }