我已经建立了一个BMI计算器。在用户输入字段中,如何限制小数点后的数字?这是我的代码:
package com.example.bmicalculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public double roundTwoDecimals(double d){
DecimalFormat roundOff = new DecimalFormat("#.##");
return Double.valueOf(roundOff.format(d));
}
public void buttonClicked(View v){
EditText editTextHeight = findViewById(R.id.userHeight);
EditText editTextWeight = findViewById(R.id.userWeight);
TextView textViewResult = findViewById(R.id.userBMI);
double height = Double.parseDouble(editTextHeight.getText().toString());
double weight = Double.parseDouble(editTextWeight.getText().toString());
double BMI = weight / (height * height);
double cBMI = roundTwoDecimals(BMI);
textViewResult.setText(Double.toString(cBMI));
editTextHeight.setText("");
editTextWeight.setText("");
}
}
请不要将其标记为重复。我已经尝试了StackOverflow中的所有方法但没有一个对我有用。
我使用了以下方法
InputFilter filter = new InputFilter() {
final int maxDigitsBeforeDecimalPoint = 4;
final int maxDigitsAfterDecimalPoint = 1;
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dStart, int dEnd) {
StringBuilder builder = new StringBuilder(dest);
builder.replace(dStart, dEnd, source.subSequence(start, end).toString());
if(!builder.toString().matches(
"(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?")){
if(source.length() == 0){
return dest.subSequence(dStart, dEnd);
}
return "";
}
return null;
}
};
和在editText 中
editTextHeight.setFilters(new InputFilter[]{filter});
editTextWeight.setFilters(new InputFilter[]{filter});
您可以使用TextWatcher.afterTextChanged((来更改输入的文本。
尝试使用这种最简单的限制小数点的方法,
double BMI = weight / (height * height);
double cBMI = Double.parseDouble(String.format("%.02f", BMI));
"%02f">将把双精度值限制为两个小数点,您可以根据需要进行更改,就像把双精度限制为三个小数点一样,您只需要更改参数ino"%03f">