public String size(int size){
String hrSize = \"\";
int k = size;
double m = size/1024;
double g = size/1048576;
double t = size/1073741824;
You are performing integer division,
i.e., 31/15 will result in 2, not 2.whatever
just append the number with D
or d
which denotes it as a double and you will be fine
double m = size/1024D;
double g = size/1048576D;
double t = size/1073741824D;
The problem is that you're using integer division. Change your code to:
double m = size/1024.0;
double g = size/1048576.0;
double t = size/1073741824.0;
In your original code, double m = size/1024
would divide the integer size
by 1024
, truncate the result to an integer, and only then convert it to double
. This is why the fractional part was getting lost.
public class FileSizeCalculator {
String[] fileSizeUnits = {"bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
public static void main(String[] args) {
FileSizeCalculator fs = new FileSizeCalculator();
String properFileSize = fs.calculateProperFileSize(2362232012l);
System.out.println("Proper file size: " + properFileSize);
}
public String calculateProperFileSize(long noOfBytes){
String sizeToReturn = "";// = FileUtils.byteCountToDisplaySize(bytes), unit = "";
double bytes = noOfBytes;
int index = 0;
for(index = 0; index < fileSizeUnits.length; index++){
if(bytes < 1024){
break;
}
bytes = bytes / 1024;
}
sizeToReturn = String.valueOf(bytes) + " " + fileSizeUnits[index];
return sizeToReturn;
}
}
Just add more file unit (if any missing), and you will see unit size up to that unit (if your file has that much length)
My basic version (you CAN define some constants instead of computing POW all the time):
public static String GetFolderSizeHuman(long aBytes)
{
if (aBytes < 1024 * 1024)
return aBytes + " KB";
else if (aBytes < Math.pow(2, 20) * 1024)
return (int) aBytes / Math.pow(2, 20) + " MB";
else if (aBytes < Math.pow(2, 30) * 1024 )
return kGbTbFormatter.format(aBytes / Math.pow(2, 30)) + " GB";
else if (aBytes < Math.pow(2, 40) * 1024)
return kGbTbFormatter.format(aBytes / Math.pow(2, 40)) + " TB";
else return "N/A (1TB?)";
}