Search code examples
javatypecasting-operator

Percentage Calculation giving me zero in Java


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


Solution

  • 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;