1
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?

manfcas
  • 1,933
  • 7
  • 28
  • 47

3 Answers3

2

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.

Community
  • 1
  • 1
luiscubal
  • 24,773
  • 9
  • 57
  • 83
1

The issue is with the following line of code

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

All values are integers so it is computing (11 + 22 + 10) / 3 as the integer value 14 by means of integer division.

If you change the divisor to a double the result will be floating point arithmetic.

calc = (n1 + n2 + n3) / 3.0;
cyroxis
  • 3,661
  • 22
  • 37
0

try to cast the integer result to double

calc =(double) (n1 + n2 + n3)/3;
Vasileios Pallas
  • 4,801
  • 4
  • 33
  • 50