[英]Limit Decimal Places in EditText
I'm using an EditText Field where the user can specify an amount of money.我正在使用 EditText 字段,用户可以在其中指定金额。
I set the inputType to numberDecimal which works fine, except that this allows to enter numbers such as 123.122 which is not perfect for money.我将 inputType 设置为 numberDecimal 可以正常工作,除了这允许输入诸如 123.122 之类的数字,这对于金钱来说并不完美。
I wrote some custom InputFilter method and it's working like this.User can 5 elements before dot and after dot-two,but not working correctly My goals are:我写了一些自定义的 InputFilter 方法,它的工作原理是这样的。用户可以在 dot-2 之前和 dot-2 之后使用 5 个元素,但不能正常工作我的目标是:
1) use should input maximum 9999.99 1) 使用时应输入最大9999.99
2) If user starting from 0 and second element is also 0,It must replace with.(for example 0.0) and after two elements after dot(like this 0.01) here is a my code 2)如果用户从0开始,第二个元素也是0,它必须替换为。(例如0.0)和点后的两个元素之后(如0.01)这是我的代码
public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
mPattern=Pattern.compile("[0-9]*" + (digitsBeforeZero-1) + "}+((\\.[0-9]*" + (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;
}
}
I'm calling this method like this我这样调用这个方法
amountValue.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});
How I can rewrite my code to solved my issues?我如何重写我的代码来解决我的问题? thanks谢谢
Your constructed regex is all wrong.您构建的正则表达式都是错误的。
The first part of your regex is this expression:正则表达式的第一部分是这个表达式:
"[0-9]*" + (digitsBeforeZero-1) + "}+"
Say digitsBeforeZero = 5
, that gets you:说digitsBeforeZero = 5
,这会让你:
[0-9]*4}+
That's not the correct regex.这不是正确的正则表达式。 The regex is supposed to be:正则表达式应该是:
[0-9]{1,5}
meaning between 1 and 5 digits.表示 1 到 5 位数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.