java - 如何限制双精度点后的输入值?
问题描述
我得到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...
那么如何在点之后实现两个双精度值的限制呢?
解决方案
推荐阅读
- reactjs - 从 ts 组件传递要在 SASS 中使用的属性
- django - 将访问令牌存储在 httponly Cookie 中,但用户仍然可以在 Chrome 开发工具的网络选项卡中看到它?
- php - 与表中的列名对应的关联数组
- c# - 找到知道开始和结束的整个路径 C#
- python - 通过在 Ansible 中附加零来将一位数转换为两位数
- angular - 如何防止角度多次登录
- javascript - 基于预定列表自动填充为用户类型的文本区域
- javascript - 浏览器控制台中的 Javascript 在一项任务中运行以填充网页女巫中的公式,多次使用不同的帖子变量重新加载
- python - 我无法在 Django 框架中打开管理页面
- c++ - 当指数是整数时 pow(x,p) 更快吗?