1

I want to display the average number in the textview. however, the output is always the integer. For example, my input num1 is 2 and 3. the output is 2.00. input: 2 and 7, the output is 4.00.

here is my code.

    <string name="ave">Average: %1$.02f</string> //in strings.xml        

    //in main function
    int num1 = Integer.parseInt(number1.getText().toString());
    int num2 = Integer.parseInt(number2.getText().toString());

    //get the average number
    float average = ( num1 + num2 ) / 2;
    ave_num.setText(getString(R.string.ave, average));
田睿霖
  • 33
  • 5

4 Answers4

1

The right side of this assignment:

float average = (num1 + num2) / 2;

consists only of integers.
So after the addition, the division will give the result of integer division.
This is how the compiler treats mathematical operations between integers.
Of course you want the result as float.
So do this:

float average = 1.0f * ( num1 + num2 ) / 2;

By multiplying with 1.0f (the f suffix denotes float) you will get the desired float result.
Or:

float average = ( num1 + num2 ) / 2f;
forpas
  • 160,666
  • 10
  • 38
  • 76
0

Use DecimalFormat

  float average = ( num1 + num2 ) / 2;
  DecimalFormat df = new DecimalFormat();
  df.setMaximumFractionDigits(2);

  System.out.println(df.format(average ));

or String.format

  String average=String.format("%.02f", average )
sasikumar
  • 12,540
  • 3
  • 28
  • 48
0

I've already tested this code:

float average = ( num1 + num2 ) / 2f;
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
-1
double roundTwoDecimals(double d)
{
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

or

String.format("Value of a: %.2f", a) // for 2 decimal number ex. 1.03

String.format("Value of a: %.3f", a) // for 3 decimal number ex. 1.003

String.format("Value of a: %02d", a) // for 2 didgit ex. 01
Vinesh Chauhan
  • 1,288
  • 11
  • 27