java要求输出小数点8位_java – Android – 如何只允许一定数量的小数位

您是否知道有任何方法可以确保用户只能输入最大小数位数的数字.

我不知道如何解决这个问题.在MS SQL数据库中我将​​从我的应用程序发送数据我有这种类型的列十进制(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)} );

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值