gnrcs
gnrcs

Reputation: 89

How do I convert a double to 2 decimal places?

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


    }

Upvotes: 1

Views: 7061

Answers (2)

Suwarto
Suwarto

Reputation: 1

You can use DecimalFormat to overcome this problem.

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

Upvotes: 0

Keyur Nimavat
Keyur Nimavat

Reputation: 3635

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

Upvotes: 4

Related Questions