I have EditText field (inputType="numberDecimal") where the user is able to input his/her rent amount. It should only allow numbers up to 2 decimals. I tried to make custom filter for this, but I can't seem to make it work.
class DecimalDigitsInputFilter(private val digitsBeforeZero: Int, private val digitsAfterZero: Int) : InputFilter {
private val pattern: Pattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?")
override fun filter(source: CharSequence?, start: Int, end: Int, dest: Spanned?, dstart: Int, dend: Int): CharSequence? {
val matcher = pattern.matcher(dest)
if (!matcher.matches()) return ""
return null
}
}
This kinda sorta works, but there is some weird interactions. For example if I input 5 digits then I cannot add the decimal point anymore, but if I have 4 digits I can add the decimal point and two decimals. Or if I input for example two digits and two decimals, lets say 55.55 then I cannot add anymore numbers to the front, even thought it should allow 5 digits before the decimal point.
Is this good way to restrict the decimals for the input or is there some better way? Can somebody help me fix this, thanks.