Android-如何只允许一定数量的小数位 [英] Android - How to only allow a certain number of decimal places

查看:90
本文介绍了Android-如何只允许一定数量的小数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道有什么方法可以确保用户只能输入最大小数位数的数字. 我不确定如何解决此问题.在MS SQL数据库中,我将从我的应用程序发送数据,我得到了具有decimal(8,3)类型的列 现在考虑最后要存储要在Android中验证的值的列的数据类型,我考虑了以下两种情况:

Do you know of any method to make sure users can only enter figures with a maximum number of decimals. I'm not sure how to address this problem. In the MS SQL database I'm going to send data from my app I've got columns with this type decimal(8,3) Now considering the data type of the column that's finally going to store the value I want to validate in Android, I've considered these two cases:

  1. 如果用户输入的数字不带小数,则最大位数必须为8
  2. 如果用户输入带小数的数字,则最大位数必须为8(包括小数点右边的数字)

现在我可以确定第一种情况,但对于第二种情况则不太确定. 将最大位数固定为固定值(例如,始终为8)是否正确?还是我应该考虑允许小数点左边最多8位,小数点右边最多3位?

Now I'm sure about the first case, but not so much about the second. Is it right to keep the number of maximum digits fixed(for example, always 8)? Or should I consider allowing a maximum of 8 digits to the left and 3 to the right of the decimal point?

无论哪种方式,这都是我在Android中一直尝试的方法:

Either way this is what I've been trying in 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中允许的总位数.

Even though, the above code handles the maximum number of decimal places. It does not limit the total number of digits allowed in the EditText.

您认为您可以帮助我改善代码,使其同时处理最大小数位数和EditText中允许的总位数吗(考虑小数点左侧和右侧的两个数字)

Do you think you could help me improve my code so that it handles both the maximum number of decimal places and the total number of digits allowed in a EditText (considering both numbers to the left and to the right of the decimal point)

好吧,现在我正在尝试JoãoSousa的建议,这是我已经尝试的方法:

Well, now I'm trying what João Sousa suggested and here's what I've tried:

1)我定义了一个实现InputFilter的类

1) I defined a class that implements 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)尝试使用这样的类:

2) Tried to use the class like this :

mQuantityEditText.setFilters(new InputFilter[] { new NumberInputFilter(8,3)} );

推荐答案

我将使用正则表达式的功能在编辑文本本身中进行过滤.首先是正则表达式:

I would go for a filter in the edit text itself with the power of regex. First the regex expression:

^\-?(\d{0,5}|\d{0,5}\.\d{0,3})$

也许有多种方法可以改善这种表达方式,但这确实有效.

Maybe there are multiple ways to improve this expression, but this does trick.

现在只需在edittext中设置输入过滤器,如下所示:

And now just set an input filter in the edittext, like this:

final String regex = "^\-?(\d{0,5}|\d{0,5}\.\d{0,3})$";
((EditText)rootView.findViewById(R.id.editText1)).setFilters(new InputFilter[] {
    new InputFilter() {
        @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(regex) ? null : "";
            }
            // removing: always accept
            return null;
        }
    }
});

顺便说一句,我刚刚测试了这段代码,它的作用是:

Btw, I just tested this code and what it does is:

  1. 用户最多可以输入8位数字;
  2. 用户输入."后,允许的最大十进制数字为8.

我正确理解了您描述的问题吗?

Did I correctly understand the problem you described?

-编辑

好的,我快到了.据我了解,decimal(8,3)表示最多8位数字,包括小数点左边或右边的数字,范围从-99999.99999999.999. 至少这是我从这句话Standard SQL requires that DECIMAL(5,2) be able to store any value with five digits and two decimals, so values that can be stored in the salary column range from -999.99 to 999.99所了解的.即使来自MySQL文档,MSSQL文档似乎也可以做到这一点.

Ok, I was almost there. From what I understand, decimal(8,3) means at most 8 digits including digits to the left or right of the decimal point, ranging from -99999.999 to 99999.999. At least that's what I understand from this sentence Standard SQL requires that DECIMAL(5,2) be able to store any value with five digits and two decimals, so values that can be stored in the salary column range from -999.99 to 999.99. Even though it's from the MySQL documentation the MSSQL docs seem to do the same.

这篇关于Android-如何只允许一定数量的小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆