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?
You can use String. format("%. 2f", d) , your double will be rounded automatically. Save this answer.
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.
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)});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With