Skip to content

Instantly share code, notes, and snippets.

@amcmobileware
Last active August 11, 2020 21:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amcmobileware/e42f376b6f8856d827564853903553db to your computer and use it in GitHub Desktop.
Save amcmobileware/e42f376b6f8856d827564853903553db to your computer and use it in GitHub Desktop.
public class DecimalDigitsInputFilter implements InputFilter {
private static String separators = "[\\.\\,]";
private final Pattern mPattern;
public DecimalDigitsInputFilter(int digitsBeforeSeparator, int digitsAfterSeparator) {
String b = "(-?\\d{1," + digitsBeforeSeparator + "})";
String a = "(\\d{1," + digitsAfterSeparator + "})";
String s = separators;
String numberRegex = new StringBuilder()
.append("(-)")
.append("|")
.append("(" + b + s + a + ")")
.append("|")
.append("(" + b + s +")")
.append("|")
.append("(" + b + ")")
.toString();
mPattern = Pattern.compile(numberRegex);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String input = dest.toString().substring(0, dstart) + source.
subSequence(start, end) + dest.toString().substring(dend);
Matcher matcher = mPattern.matcher(input);
if (!matcher.matches()) {
return "";
}
return null;
}
}
@abigaillafay
Copy link

It's worked like a charm, thank you! I have a question: How can i achieve that comma (",") displayed on the screen not dot (".") because in Hungary we using comma as decimal separator.

@amcmobileware
Copy link
Author

amcmobileware commented May 28, 2019

android:digits="0123456789," setting can be add to the EditText. Moreover, instead of returning null in the DecimalDigitsInputFilter, you can return source.replace(".", ",")

according to the answer https://stackoverflow.com/a/40020731/1510222 there is no way to hide dot in a standard keyboard

@abigaillafay
Copy link

Thank you for your great code and your help! Meanwhile i understand your code (i'm very newby in java & android) and i used the same solution what you wrote (...because it's trivial but not first sight for me :) )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment