Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@abigaillafay abigaillafay commented May 24, 2019

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

This comment has been minimized.

Copy link
Owner Author

@amcmobileware 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

This comment has been minimized.

Copy link

@abigaillafay abigaillafay commented May 29, 2019

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