1

my code:
long totalVolume = sellVolume + buyVolume; float sellPercent = (float)(sellVolume / totalVolume); float buyPercent = (float)(buyVolume / totalVolume);

All the variable are long in the first line of code, and then I am trying to calculate the Percentage of it.... but java returns me zero only ... why is it so - Am i doing something wrong in typecasting

Abdeali Chandanwala
  • 8,449
  • 6
  • 31
  • 45
  • 3
    The `float` cast is too late. The division is being performed in `long`. – Jim Garrison Mar 14 '16 at 07:28
  • You are explicitly only casting after you have performed the integer division, don't do that. Also don't use `float` as it imprecise, at least using `double` or `BigDecimal`. – Peter Lawrey Mar 14 '16 at 07:29
  • Possible duplicate of [Why does the division of two integers return 0.0 in Java?](http://stackoverflow.com/questions/4931892/why-does-the-division-of-two-integers-return-0-0-in-java) – Erwin Bolwidt Mar 14 '16 at 07:44

1 Answers1

6

You should cast one of the operands to float before performing the division in order to perform floating point division (instead of long division).

float sellPercent = (float)sellVolume / totalVolume;
float buyPercent = (float)buyVolume / totalVolume;
Eran
  • 387,369
  • 54
  • 702
  • 768