-1

I do not why the below mathematical operation gives me 0.0

Mathematical_expression:

double percentageAmongAll = ((itemClickedID+1)/(parent.getCount()));

Logcat_Output:

06-14 13:46:53.176: I/MySavedLocation(19361): parent.getCount() = 3
06-14 13:46:53.176: I/MySavedLocation(19361): itemClickedID+1 = 2
06-14 13:46:53.176: I/MySavedLocation(19361): percentageAmongAll = 0.0
rds
  • 26,253
  • 19
  • 107
  • 134
Amrmsmb
  • 1
  • 27
  • 104
  • 226

1 Answers1

4

itemClickedID+1 and parent.getCount() are integer expressions. Integer division always returns integers, so 2/3 returns 0 which is then converted to 0.0.

double percentageAmongAll =  ((double) itemClickedID+1)/(parent.getCount());

This will cast itemClickedId to a double, so a double division will be performed.

Tobias
  • 7,723
  • 1
  • 27
  • 44
  • 2
    `(itemClickedID+1.0)/(parent.getCount())` would do it as well. The `1.0` turns the numerator into a double and so the whole expression is calculated as a double, not an integer. – rossum Jun 14 '14 at 10:59
  • Yes, of course, there are dozens of ways to achieve it. – Tobias Jun 14 '14 at 10:59