Android:将文本字段限制为一个小数点

时间:2013-06-16 11:43:31

标签: java android regex

如何将EditText字段限制为仅一个小数点。假设用户应在(.)[decimal].

之后仅输入一位数/数字

用户输入:1.92 [Its invalid] 用户输入:1.9 [Its Valid]

以下是我正在使用的正则表达式。

mPattern = Pattern.compile("[0-9]*+((\\.[0-9]{0," + (digitsAfterZero - 1) + "})?)||(\\.)?");

我遇到小数问题,如果用户输入23.1就可以了,但同一位用户可以输入2.31

如何限制用户在十进制后只输入一个数字/位数。

2 个答案:

答案 0 :(得分:3)

如何使用正则表达式..

public class DecimalDigitsFilter implements InputFilter {

Pattern pattern;

public DecimalDigitsFilter(int digitsBeforeZero,int digitsAfterZero) {
    pattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned destination, int destinationStart, int destinationEnd) {

    Matcher matcher=pattern.matcher(destination);       
    if(!matcher.matches())
        return "";
    return null;
   }
}

然后将其称为..

editText.setFilters(new InputFilter[] {new DecimalDigitsFilter(5,1)}); //5 before point and 1 after point.Change it as your need

答案 1 :(得分:0)

TextWatcher添加到textView并使用它的方法来防止在点后面输入多个数字。