单选按钮 - 小数位选项



我正在制作一个程序,为你做某些类型的数学运算。用户输入一个数字并点击一个按钮,将他们带到另一个活动,并显示答案和公式等。但有时答案有一个小数,小数点后有疯狂的数字。

现在,我已经知道如何更改小数点后的数字数量,但我想使用与 editText 同一页面上的单选按钮为用户提供他们想要在小数点后多少位数字的选项。

我该怎么做?

这就是我到目前为止所拥有的....

带单选按钮的输入页-

公共无效点击(查看视图({

boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()){
case R.id.radioButton1:
if (checked){
Intent check = new Intent(this, Output.class);
String value = "0.0";
check.putExtra("PATTERN", value);
}
break;
case R.id.radioButton2:
if (checked){
Intent check = new Intent(this, Output.class);
String value = "0.00";
check.putExtra("PATTERN", value);
}
break;
case R.id.radioButton3:
if (checked){
Intent check = new Intent(this, Output.class);
String value = "0.000";
check.putExtra("PATTERN", value);
}
break;
case R.id.radioButton4:
if (checked){
Intent check = new Intent(this, Output.class);
String value = "0.000000000";
check.putExtra("PATTERN", value);
}
break;
}
}

输出页面-

Intent intent = getIntent();
String pattern = intent.getStringExtra("PATTERN");
String answerS = intent.getStringExtra("MESSAGE");
double fix = Double.parseDouble(answerS);
DecimalFormat dFormatter = new DecimalFormat(pattern);
String answerSS = "" + dFormatter.format(fix);
TextView answer = findViewById(R.id.answer);
answer.setText(answerSS);

这是布局和我想要的选项

使用十进制格式化程序 取决于每个单选按钮:

double number = 3.14159265359;
DecimalFormat numberFormat = new DecimalFormat("#.0000");
System.out.println(numberFormat.format(number));

将输出:3.1415

您可以通过使用或多或少的0或在分隔符后使用 # 来扩展它,例如:

double number = 3.1500000000;
DecimalFormat numberFormat = new DecimalFormat("#.####");
System.out.println(numberFormat.format(number));

留给您输出3.15

改变这个东西。

switch (view.getId()){
case R.id.radioButton1:
if (checked){
Intent check = new Intent(this, Output.class);
String value = "0";
check.putExtra("PATTERN", value);
}
break;
case R.id.radioButton2:
if (checked){
Intent check = new Intent(this, Output.class);
String value = "00";
check.putExtra("PATTERN", value);
}
break;
case R.id.radioButton3:
if (checked){
Intent check = new Intent(this, Output.class);
String value = "000";
check.putExtra("PATTERN", value);
}
break;
case R.id.radioButton4:
if (checked){
Intent check = new Intent(this, Output.class);
String value = "000000000";
check.putExtra("PATTERN", value);
}
break;
}


Intent intent = getIntent();
String pattern = intent.getStringExtra("PATTERN");
String answerS = intent.getStringExtra("MESSAGE");
double fix = Double.parseDouble(answerS);
DecimalFormat dFormatter = new DecimalFormat("#."+pattern);
String answerSS = "" + dFormatter.format(fix);
TextView answer = findViewById(R.id.answer);
answer.setText(answerSS);

最新更新