I have a utility function that will display a filesize in an appropriate form like Windows Explorer does, i.e; convert it to nearest KB, MB, GB etc. I wanted to know if the code that i wrote is correct, and if it can be made simpler.
The function that i wrote is as follows :
public static function formatFileSize(bytes:int):String
{
if(bytes < 1024)
return bytes + " bytes";
else
{
bytes /= 1024;
if(bytes < 1024)
return bytes + " Kb";
else
{
bytes /= 1024;
if(bytes < 1024)
return bytes + " Mb";
else
{
bytes /= 1024;
if(bytes < 1024)
return bytes + " Gb";
}
}
}
return String(bytes);
}
While it does the job for me at the moment, i feel it could be written in an even simpler way and maybe even optimized.
thanks in advance
? :
operators instead of if(){}else{} – As