android 一位小数_Android-如何只允许一定数量的小数位

您是否知道确保用户只能输入最大小数位数的数字的任何方法。我不确定如何解决这个问题。在MS

SQL数据库中,我将从应用程序中发送数据,我得到了具有这种类型的列。decimal(8,3)

现在考虑最终要存储要在Android中验证的值的列的数据类型,我已经考虑了这些两种情况:

如果用户输入不带小数的数字,则最大位数必须为8

如果用户输入带小数的数字,则最大位数必须为8(包括小数点右边的数字)

现在,我可以确定第一种情况,而对于第二种情况则不是那么确定。 保持最大位数固定(例如,始终为8)是否正确?

还是我应该考虑允许小数点左边最多8位,小数点右边最多3位?

无论哪种方式,这都是我在Android中一直尝试的方法:

mQuantityEditText.addTextChangedListener(new TextWatcher() {

@Override

public void afterTextChanged(Editable s) {

String str = mQuantityEditText.getText().toString();

DecimalFormat format = (DecimalFormat) DecimalFormat

.getInstance();

DecimalFormatSymbols symbols = format.getDecimalFormatSymbols();

char sep = symbols.getDecimalSeparator();

int indexOFdec = str.indexOf(sep);

if (indexOFdec >= 0) {

if (str.substring(indexOFdec, str.length() - 1).length() > 3) {

s.replace(0, s.length(),

str.substring(0, str.length() - 1));

}

}

}

@Override

public void beforeTextChanged(CharSequence s, int start, int count,

int after) {

}

@Override

public void onTextChanged(CharSequence s, int start, int before,

int count) {

}

});

即使上面的代码处理最大的小数位数。它不限制EditText中允许的总位数。

您是否认为可以帮助我改善代码,使其同时处理最大小数位数和EditText中允许的总位数(考虑小数点左侧和右侧的两个数字)

编辑

好吧,现在我正在尝试JoãoSousa的建议,这是我已经尝试的方法:

1)我定义了一个实现InputFilter的类

public class NumberInputFilter implements InputFilter {

private Pattern mPattern;

public NumberInputFilter(int precision, int scale) {

String pattern="^\\-?(\\d{0," + (precision-scale) + "}|\\d{0," + (precision-scale) + "}\\.\\d{0," + scale + "})$";

this.mPattern=Pattern.compile(pattern);

}

@Override

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

if (end > start) {

// adding: filter

// build the resulting text

String destinationString = destination.toString();

String resultingTxt = destinationString.substring(0, destinationStart) + source.subSequence(start, end) + destinationString.substring(destinationEnd);

// return null to accept the input or empty to reject it

return resultingTxt.matches(this.mPattern.toString()) ? null : "";

}

// removing: always accept

return null;

}

}

2)尝试使用这样的类:

mQuantityEditText.setFilters(new InputFilter[] { new NumberInputFilter(8,3)} );

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值