Search code examples
javaandroidandroid-edittextformatstring-formatting

Android edittext: Formatting number


I have a edittext, and if I enter input number as 100000, the result must be 100.000, and if I enter input as 1000000, the result must be 1.000.000.

After every 3 characters from the last to beginning must have a "."

Here is my code:

tambah = (EditText)rootView.findViewById(R.id.total);
tambah.setOnFocusChangeListener(new OnFocusChangeListener(){
       public void onFocusChange(View v, boolean hasFocus) {
              // ...
       }

Solution

  • Here is something I use to for dollar input. It makes sure that there are only 2 places past the decimal point at all times. You should be able to adapt it to your needs by removing the $ sign.

    amountEditText.setRawInputType(Configuration.KEYBOARD_12KEY);
    amountEditText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {}
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(!s.toString().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
        {
            String userInput= ""+s.toString().replaceAll("[^\\d]", "");
            StringBuilder cashAmountBuilder = new StringBuilder(userInput);
    
            while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
                cashAmountBuilder.deleteCharAt(0);
            }
            while (cashAmountBuilder.length() < 3) {
                cashAmountBuilder.insert(0, '0');
            }
            cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
            cashAmountBuilder.insert(0, '$');
    
            amountEditText.setText(cashAmountBuilder.toString());
            // keeps the cursor always to the right
            Selection.setSelection(amountEditText.getText(), cashAmountBuilder.toString().length());
    
        }
    
    }
    });