Question

I have running android program which an editText takes one of its input as a double/decimal value. what i want to do is to restrict user from entering any other digit than 0 or 5 after decimal. like 1.5 , 1.0 , 2.5 , 2.0 and so on i have successfully restricted the user to put value upto one decimal place. is there any way i can get input either 0 or 5 after decimal or i can put a validation if user inputs 1.2 or some other value other than 5 or 0 after decimal.

the code to restrict is

public class DecimalDigitsInputFilter implements InputFilter {

            Pattern mPattern;

            public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
                mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
            }

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

                    Matcher matcher=mPattern.matcher(dest);       
                    if(!matcher.matches())
                        return "";
                    return null;
                }

            }

and i use it as

txtLdays.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,1)});
Was it helpful?

Solution

What I would do is a quite simple test. Once you have validated you input like you have done, you can just test to see if the inputted number can be divided by 0.5 and the result is a number without fractions. For example, if the user inputted 2.5 - you divide it by 0.5 and you get 5. that is OK. If the user inputted 2.3, and you divide by 0.5 - you get a fraction, which is not OK.

Follow this suggestion of code:

Double input = Double.valueOf(txtLdays.getText.toString());
if (input % 0.5 == 0){ //Check if you number divides by 0.5 with no fraction
//Your number divides by 0.5, input is ok
} else {
//Your number does not divide by 0.5, please re-enter number
}

Hope this helped!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top