首页 > 解决方案 > 如何限制双精度点后的输入值?

问题描述

我得到EditText了双重价值。
问题是我想将点后的数字限制为两个这样的:“#.##”。现在用户可以输入像 10.9237474 这样的值,但我想让用户在点后只输入 10.92。
我试过InputFilter

 enter_price.setFilters(new InputFilter[]{new InputFilter.LengthFilter(2)});

但是这个函数是指所有数字而不考虑点符号。我也在使用TextWatcher并尝试过这样的事情:

public TextWatcher Sum_Edit = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            String x = s.toString();
            if(x.contains(".")){
              // here tried to set input filter also like above
            }

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            amountSet();

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

CharSequence s另一个问题是我在TextWatcher第一次使用后无法清除。因此,当我使用“BackSpace”清除时,我EditText只能输入两个数字。在运行应用程序后的第一次,我可以输入很多数字。就这样。
在用户输入正确的价格后,给定的值我从字符串解析为加倍并保存在数据库中。所以我有这样的东西:

String get_price_field = enter_price.getText().toString().trim();
Double price_field = Double.parseDouble(get_price_field);
//Then save double value to db.

我不想这样:

String get_price_field = enter_price.getText().toString().trim();
Double price_field = Double.parseDouble(get_price_field);
Format to String  like this: 
String formattedString = String.format("%.02f", price_field)
Then back to double
Double price_field2 = Double.parseDouble(formattedString);
Beacuse program executes with no sense the same work...

那么如何在点之后实现两个双精度值的限制呢?

标签: javaandroiddouble

解决方案


推荐阅读