How to limit decimal points to + one digit per digit
php小编鱼仔带来的Java问答:如何实现将小数点限制为每个数字后只能保留一位?这是许多Java开发者在处理数字格式化时经常遇到的问题。在实际项目中,对小数点的控制是非常重要的,尤其是涉及金额、货币等需要精确计算的场景。接下来,我们将通过简单易懂的例子,详细介绍在Java中如何实现这一需求。
问题内容
我正在 java/android studio 中编写一个计算器,我遇到了每个数字只需要一位小数点的问题。类似于 1.2,而不是 1.2.3。允许用户在计算器中使用小数或自然数,但是,一旦用户按下点(“.”)符号,就无法对该特定数字再次重复。
我对其进行编码以显示错误(这不起作用),并且用户不应该在数字的第一个小数点之后添加另一个小数点,而不是显示错误。它需要适用于 1.1 + 1.1,但不适用于 1.1.1。或 1.1。等等
我尝试将此作为代码的一部分,但它不起作用。就像,它不断禁用我的等于按钮,即使我已经在第一次警告后立即编写了它。
Pattern p; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); p = Pattern.compile("(\\d*(\\.\\d*)?([+\\-*%\\]|$))*"); UserInput = findViewById(R.id.ed_calculation_input); UserInput.setShowSoftInputOnFocus(false); tvCalculationOutput = findViewById(R.id.tv_calculation_output); edUserInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Matcher m = p.matcher(edUserInput.getText().toString()); if(!m.matches()) { edUserInput.setError("Enter valid no"); btnEqual.setEnabled(false); } else { btnEqual.setEnabled(true); } } @Override public void afterTextChanged(Editable s) { } });
解决方法
这个问题的解决方案相当简单。您已选择 edittext
作为数字的输入,不是吗?然后您所要做的就是添加行
<EditText ... android:inputType="numberDecimal" ... />
在 xml 布局文件中,防止数字有多个小数点(或字母或其他符号)。
The above is the detailed content of How to limit decimal points to + one digit per digit. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
