[英]How do I convert a double to 2 decimal places?
这是代码:如何让它只显示小数点后两位? 当我使用String.format("%.2f", maltRequiredString);
时,我的应用程序崩溃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");
}
记住你不能使用
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));
您可以使用 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.