I’m having an odd issue in which my math inside a for loop will not calculate at all until the very last iteration, at which point it comes out as 100%. The equation I’m using is a simple percentage equation to calculate how much of an array of files has been processed thus-far. My code is below:
for(int z=0;z<theFiles.size();z++) {
...
System.out.println(z); // Prints out the current iteration.
System.out.println(theFiles.size()); // Prints out the length of the array (35 in my test sample).
double test = Math.abs(z / theFiles.size() * 100); // Calculation to find the percentage of 100 the current iteration is (this is where things seem to break). Comes out as 0 if it's set as an int also.
System.out.println(test); // Prints out the percentage complete for this iteration.
}
Anyone have an idea why the variable “test” keeps coming out 0.0? I recall having a similar problem to this in JavaScript, but I’m not sure how to fix it in Java and forgot how I had done so in JS.
It is due to integer divison. Cast one of the value to
doubleExample:
As per JLS 15.17.2