0

I'm trying to find a ratio between a song's current position and its total playing time. long pTime = player.getCurrentBufferedTimeMcsec(); long pos = player.getCurrentPosition(); return (int)(pos/pTime * 1000000l);

The return expression is evaluated as zero. How can i fix this? I'm guessing it's a mixture of what type I use and concatenation, right?

Thanks!

Edit I already checked and the "player.get" calls return values, but once divided yield a decimal (like 0.06) before it is multiplied.

theSiTi92
  • 3
  • 2

2 Answers2

2

The problem is here:

pos/pTime

Both operands are long, so the result with be long, which will truncate any fractional part. If pTime is greater than pos, the result of the division (and of course the final result) will be zero.

Change the code to allow a floating point result by casting one of the operands to a floating point type:

return (int)((double)pos/pTime * 1000000l);

When one of the operands is double, the result will be double.


Additional tip: Don't use lowercase l for long constants - it looks like a 1. Use uppercase 1000000L, or in this case drop the L altogether as it's unnecessary, because 1000000 is a valid int, which will be safely promoted to long or double anyway:

    return (int)((double)pos/pTime * 1000000);
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Or, to avoid floating point entirely: `1000000l * pos/pTime`. – Thomas Jan 28 '15 at 01:02
  • Thanks, sorry i thaught i tried this but it was in the eclipse expresions window... dont know what happened there, but thanks all the same, and sorry for the stupid question. – theSiTi92 Jan 28 '15 at 01:04
0

Cast either pos or pTime to double. You are getting integral truncation on division.

user207421
  • 305,947
  • 44
  • 307
  • 483