Limit Decimal Places in Android EditText(在 Android EditText 中限制小数位数)
问题描述
我正在尝试编写一个可以帮助您管理财务的应用程序.我正在使用 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 中限制小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Android EditText 中限制小数位数


基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 大摇大摆的枚举 2022-01-01