Syed Raza
Syed Raza

Reputation: 331

How to find Percentage in java my code giving error?

I am trying to get percentage but my code is giving "0.0" while both totalMemory and usageMemory have values I also set 4 decimal places, also but result is "0.0000" my code is,

private static long maxMemory=0;
private static long freeMemory=0;
private static long totalMemory=0;
private static long usageMemory=0;
private static double Percentage;

Runtime runtime=Runtime.getRuntime();
maxMemory=runtime.maxMemory();
freeMemory=runtime.freeMemory();
totalMemory=runtime.totalMemory();
usageMemory=totalMemory-freeMemory;
Percentage=((usageMemory/totalMemory)*100.0);
//NumberFormat percentage =NumberFormat.getPercentInstance();
//percentage = new DecimalFormat("0.0#%");
//String pr = percentage.format(Percentage);
System.out.print(Percentage);
System.out.print("Total Memory:"+totalMemory+"\n");
System.out.print("Memory Usage:"+usageMemory+"\n");

please help me what I'm doing wrong, any help in this regard is greatly appreciated.

Thanks in advance !

Upvotes: 1

Views: 2927

Answers (3)

HpTerm
HpTerm

Reputation: 8281

As @JeromeC said. In the "division" (usageMemory/totaMemory) this is an integerdivision giving 0. You need to first cast the long to double, only then do the division.

Note that the convertion from Long to double is automatic in java. You don't need specific casting. So simply redefine the variable as double instead of Long.

private static double maxMemory=0;
private static double freeMemory=0;
private static double totalMemory=0;
private static double usageMemory=0;

but perhaps in you case the best is to not do anything but change the order. Do the multiplication before the division.

Percentage=((100.0*usageMemory)/(100.0*totalMemory));

to be verified

Upvotes: 0

Jerome Cance
Jerome Cance

Reputation: 8183

This is because you use long type. Long type does not handle decimal.

Use double instead long

I explain : dividing two long results in one long (and so it is rounded before multiplying by 100).

The code :

double totalMemory;
double freeMemory;....

totalMemory=runtime.getTotalMemory()...

Or if you want to keep long type:

percentage=(((double)usageMemory/(double)totalMemory)*100d);

Upvotes: 5

Isaac
Isaac

Reputation: 2721

convert/cast usageMemory and totalMemory to double.

Upvotes: 0

Related Questions