Issue
Here is the code:
How do I make it come out as only 2 decimal places?
My app crashes when I use 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");
}
Solution
Remember you can't use
String.format("%.2f", maltRequiredString);
Because maltRequiredString is string. Correct coding is that you must use float in this function and for that you have to convert your string to float
float f = Float.valueOf(maltRequiredString);
String test = String.format("%.02f", f);
You can also use this technique for making it 2 decimal
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f));
Answered By - Keyur Nimavat Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.