最近公司有个数入金额的问题 后台数据库说小数点不占长度,当时内心是懵逼的 还有这种情况 安卓小数点肯定占的 当时设置
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(2),new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String lastInputContent = dest.toString();
if (source.equals(".") && lastInputContent.length() == 0) {
return "0.";
}
if (source.equals("0") && lastInputContent.length() == 0) {
return "";
}
if (lastInputContent.contains(".")) {
int index = lastInputContent.indexOf(".");
if (dend - index >= 2 + 1) {
return "";
}
}
return null;
}
}});
导致小数点前只能输入一位或者小数点之后只能设置一位 这很尴尬呀 心里想着这怎么办 在网上搜查一番
看到这位前辈的博客
https://www.jianshu.com/p/dbcd5d4396fc
相出来如下的判断 ,如有错误欢迎指正,此纪录只为学习 如有侵权请通知 立即删除
public class DecimalBeforeAndRearInputFilter implements InputFilter {
private static final int DEFAULT_MAX_INTEGER_LENGTH = 6;
private static final int DEFAULT_DECIMAL_NUMBER = 2;
/**
* 保留小数点后多少位
*/
private int mDecimalNumber = DEFAULT_DECIMAL_NUMBER;
/**
* 允许最大的整数多少位
*/
private int mMaxIntegralLength = DEFAULT_MAX_INTEGER_LENGTH;
public DecimalBeforeAndRearInputFilter(int mDecimalNumber, int mMaxIntegralLength) {
this.mDecimalNumber = mDecimalNumber;
this.mMaxIntegralLength = mMaxIntegralLength;
}
public DecimalBeforeAndRearInputFilter() {
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
String lastInputContent = dest.toString();
if (source.equals(".") && lastInputContent.length() == 0) {
return "0.";
}
if (source.equals("0") && lastInputContent.length() == 0) {
return "";
}
if (lastInputContent.contains(".")) {
int index = lastInputContent.indexOf(".");
if (dend - index >= mDecimalNumber + 1) {
return "";
}
} else if (!source.equals(".") && lastInputContent.length() > mMaxIntegralLength - 1) {
return "";
}
return null;
}
}
网友评论