这是代码:
如何将其显示为仅小数点后2位?
我使用String.format("%.2f", maltRequiredString);
public class MainActivity extends AppCompatActivity {
EditText batchVolEditText;
EditText ogEditText;
EditText bheEditText;
TextView maltRequiredTextView;
public void calculate(View view) {
String batchVolString = batchVolEditText.getText().toString();
String ogString = ogEditText.getText().toString();
String bheString = bheEditText.getText().toString();
double batchVolDouble = Double.parseDouble(batchVolString);
double ogDouble = Double.parseDouble(ogString);
double bheDouble = Double.parseDouble(bheString);
double specificGravity = 0.96;
double maltRequired = (batchVolDouble * ogDouble * specificGravity) / bheDouble;
String maltRequiredString = Double.toString(maltRequired);
maltRequiredTextView.setText(maltRequiredString + "kg");
}
答案 0 :(得分:0)
请记住,您无法使用
String.format("%.2f", maltRequiredString);
因为maltRequiredString是字符串。正确的编码是你必须在这个函数中使用float,为此你必须将你的字符串转换为float
float f = Float.valueOf(maltRequiredString);
String test = String.format("%.02f", f);
您也可以使用此技术将其设为2十进制
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f));
答案 1 :(得分:0)
您可以使用DecimalFormat来解决此问题。
//Make a new instance df that has 2 decimal places pattern.
Decimalformat df = new DecimalFormat("#.##");
// converting maltRequired form double to string.
String maltRequiredString = df.format(maltRequired);
// then set the value of maltRequiredString to the TextView.
maltRequiredTextView.setText(String.valueOf(maltRequiredString));