40

I am trying to calculate % of used diskspace in Windows and totaldrive denotes total diskspace of c drive in Long and freedrive dentoes free space in Long.

 long totaloccupied = totaldrive - freedrive;

Here calculating % of usage

 Long Percentageused =(totaloccupied/totaldrive*100);
 System.out.println(Percentageused);

The print statement returns 0. Can someone help as I am not getting the desired value

user1815823
  • 617
  • 2
  • 8
  • 14

3 Answers3

67

You are probably dividing a long with a long, which refers to (long/long = long) operation, giving a long result (in your case 0).

You can achieve the same thing by casting either operand of the division to a float type.

Long Percentageused = (long)((float)totaloccupied/totaldrive*100);
Lake
  • 4,072
  • 26
  • 36
7

You are doing integer division! Since totaloccupied is smaller than totaldrive, the division of both gives the answer 0. You should convert to double first:

double percentageUsed = 100.0 * totalOccupied / totalDrive;

Note that adding the decimal point to the 100 ensures it is treated as a double.

gdiazc
  • 2,108
  • 4
  • 19
  • 30
1

That will be evaluated left to right, the first integer division will return 0 (e.g. 8/10 evaluates to 0). Either convert values to floats or do 100*a/b. Floats will give you a more precise result.

Jason C
  • 38,729
  • 14
  • 126
  • 182
  • `float` will *not* give a more precise result if the numbers involved are large. – paddy Aug 08 '13 at 02:41
  • It will if you do (float)(100*a)/(float)b. The two sides will differ by a relatively small order of magnitude, which is where most precision loss occurs. – Jason C Aug 08 '13 at 02:46
  • 1
    BTW, whoever came through and down voted every answer here, please leave a constructive comment. – Jason C Aug 08 '13 at 02:47
  • 2
    If the objective is an integer percentage, the 100*a/b solution, with a and b both long, would work well. Float or double is only needed to get answers like "85.5%". – Patricia Shanahan Aug 08 '13 at 02:49