Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android edittext two decimal places

I have an editText where the user can enter an amount. So I want that this editText doesn't allow the user to enter more than two decimal places.

Example : 23.45 (not be 23.4567)

What's the best way to implement something like that?

like image 260
Elias Dolinsek Avatar asked Feb 12 '18 18:02

Elias Dolinsek


People also ask

How do I get Android to only have 2 decimal places?

You can use String. format("%. 2f", d) , your double will be rounded automatically. Save this answer.

How do you display upto 2 decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.


1 Answers

You should use InputFilter here is an example

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;
    }

}

you can use it like this

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});
like image 88
lib4 Avatar answered Oct 21 '22 04:10

lib4