Search code examples
androidandroid-studioandroid-edittextdecimaluser-input

How to limit values after decimal point in editText in android?


I have built a BMI calculator. In the user input field, how do I limit the digits after decimal point? Here is my code:

package com.example.bmicalculator;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.text.DecimalFormat;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public double roundTwoDecimals(double d){

        DecimalFormat roundOff = new DecimalFormat("#.##");
        return Double.valueOf(roundOff.format(d));
    }

    public void buttonClicked(View v){

        EditText editTextHeight = findViewById(R.id.userHeight);
        EditText editTextWeight = findViewById(R.id.userWeight);

        TextView textViewResult = findViewById(R.id.userBMI);

        double height = Double.parseDouble(editTextHeight.getText().toString());
        double weight = Double.parseDouble(editTextWeight.getText().toString());

        double BMI = weight / (height * height);

        double cBMI = roundTwoDecimals(BMI);

        textViewResult.setText(Double.toString(cBMI));

        editTextHeight.setText("");
        editTextWeight.setText("");

    }
}

Please don't mark it as a duplicate. I've already tried all methods which are there in the StackOverflow but none of them worked for me.

I have used the below method

    InputFilter filter = new InputFilter() {

        final int maxDigitsBeforeDecimalPoint = 4;
        final int maxDigitsAfterDecimalPoint = 1;

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dStart, int dEnd) {

            StringBuilder builder = new StringBuilder(dest);
            builder.replace(dStart, dEnd, source.subSequence(start, end).toString());

            if(!builder.toString().matches(
                    "(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?")){

                if(source.length() == 0){
                    return dest.subSequence(dStart, dEnd);
                }
                return "";
            }
            return null;
        }
    };

and in editText

editTextHeight.setFilters(new InputFilter[]{filter});
editTextWeight.setFilters(new InputFilter[]{filter});

Solution

  • You can use TextWatcher.afterTextChanged() to alter the entered text.