問題描述
我正在嘗試編寫一個可以幫助您管理財務的應用程序.我正在使用 EditText
字段,用戶可以在其中指定金額.
I'm trying to write an app that helps you manage your finances. I'm using an EditText
Field where the user can specify an amount of money.
我將 inputType
設置為 numberDecimal
效果很好,除了這允許人們輸入諸如 123.122
之類的數字,這并不適合錢.
I set the inputType
to numberDecimal
which works fine, except that this allows people to enter numbers such as 123.122
which is not perfect for money.
有沒有辦法將小數點后的字符數限制為兩個?
Is there a way to limit the number of characters after the decimal point to two?
推薦答案
這是一個示例 InputFilter,它只允許小數點前最多 4 位,小數點后最多 1 位.
Here is a sample InputFilter which only allows max 4 digits before the decimal point and max 1 digit after that.
edittext 允許的值:555.2、555、.2
Values that edittext allows: 555.2, 555, .2
編輯文本塊的值:55555.2、055.2、555.42
InputFilter filter = new InputFilter() {
final int maxDigitsBeforeDecimalPoint=4;
final int maxDigitsAfterDecimalPoint=1;
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dstart, dend, source
.subSequence(start, end).toString());
if (!builder.toString().matches(
"(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"
)) {
if(source.length()==0)
return dest.subSequence(dstart, dend);
return "";
}
return null;
}
};
mEdittext.setFilters(new InputFilter[] { filter });
這篇關于在 Android EditText 中限制小數位數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!