限制 Android EditText 中的小数位

2022-08-31 07:50:19

我正在尝试编写一个应用程序来帮助您管理财务。我正在使用一个字段,用户可以在其中指定金额。EditText

我设置了哪个工作正常,除了这允许人们输入数字,例如对于金钱来说并不完美。inputTypenumberDecimal123.122

有没有办法将小数点后的字符数限制为两个?


答案 1

更优雅的方法是使用正则表达式(正则表达式),如下所示:

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;
    }

}

要使用它,请执行以下操作:

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});

答案 2

不使用正则表达式的更简单的解决方案:

import android.text.InputFilter;
import android.text.Spanned;

/**
 * Input filter that limits the number of decimal digits that are allowed to be
 * entered.
 */
public class DecimalDigitsInputFilter implements InputFilter {

  private final int decimalDigits;

  /**
   * Constructor.
   * 
   * @param decimalDigits maximum decimal digits
   */
  public DecimalDigitsInputFilter(int decimalDigits) {
    this.decimalDigits = decimalDigits;
  }

  @Override
  public CharSequence filter(CharSequence source,
      int start,
      int end,
      Spanned dest,
      int dstart,
      int dend) {


    int dotPos = -1;
    int len = dest.length();
    for (int i = 0; i < len; i++) {
      char c = dest.charAt(i);
      if (c == '.' || c == ',') {
        dotPos = i;
        break;
      }
    }
    if (dotPos >= 0) {

      // protects against many dots
      if (source.equals(".") || source.equals(","))
      {
          return "";
      }
      // if the text is entered before the dot
      if (dend <= dotPos) {
        return null;
      }
      if (len - dotPos > decimalDigits) {
        return "";
      }
    }

    return null;
  }

}

要使用:

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(2)});

推荐