How do I convert a double to 2 decimal places? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How do I convert a double to 2 decimal places? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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");



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));
We are here to answer your question about How do I convert a double to 2 decimal places? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji