2
    public int total;
    public int likes;
    public double average;

    total = 5;
    likes = 21;

    average = likes / total;

    Log.d("Average", average);

Hi, average = likes / total should return 4.2, however, its running 4.0. How can I keep it as 4.2 and not 4.0?

Alexandre Neukirchen
  • 2,713
  • 7
  • 26
  • 36
Josh Joe
  • 65
  • 1
  • 2
  • 9

2 Answers2

2
average = (double)likes / total;
Anurag Aggarwal
  • 247
  • 1
  • 5
2

Calculations using only integers causes the end result to be integer, even if later you assign it to a floating point value like double. Integer division works by counting how many times the denominator can fit entirely in the numerator.

To resolve, you have to cast at least one of the 2 operands in the division so that the division is performed already in double precision (numbers inside arithmetic operations are automatically casted to a type that allow greater precision than its operands, if at least one of the operands have that precision):

average = (double)likes / total;

or

average = likes / (double) total;

Please note that this is different than average = (double) (likes / total);, which would cast the result after it has already been rounded down.

CoffeDeveloper
  • 7,961
  • 3
  • 35
  • 69
AntonH
  • 6,359
  • 2
  • 30
  • 40