stickoverflow - 1 year ago 100

Android Question

`public void onButtonClick(View v) {`

int n1, n2, n3;

double calc;

EditText e1 = (EditText)findViewById(R.id.first_grade);

EditText e2 = (EditText)findViewById(R.id.second_grade);

EditText e3 = (EditText)findViewById(R.id.third_grade);

TextView t1 = (TextView)findViewById(R.id.calculate);

n1 = Integer.parseInt(e1.getText().toString());

n2 = Integer.parseInt(e2.getText().toString());

n3 = Integer.parseInt(e3.getText().toString());

calc = (n1 + n2 + n3)/3;

t1.setText(String.format("%.2f", calc));

}

This is my code and I have tried DecimalFormat as well, but none of the solutions from the stackoverflow work for me.

If I put 11, 22, 10 respectively as an input, I should get a result of 14.333333, but I am getting 14.00 for the result.

Anyone know how to fix this error? Or have solution to this?

Answer Source

Since the variables `n1`

, `n2`

and `n3`

are `ints`

, their sum and subsequent division are integer as well. As such, the result is truncated to the integer.

To get the accurate result, you should force the division to be a floating-point one. To do this, one of the operands should be a double. You can force this by replacing `3`

with `3.0`

```
(n1 + n2 + n3) / 3.0
```

Next, is how can we round the result to two decimal digits. We can multiply the result by 100, perform the integer division and only then divide by 100 and convert to double.

```
((n1 + n2 + n3) * 100 / 3) / 100.0
```

You can see additional ways to round in this question.