将字节转换为 kb、mb、gb 等的 ActionScript 代码
问题描述:
我有一个实用函数,可以像 Windows 资源管理器那样以适当的形式显示文件大小,即;将其转换为最接近的 KB、MB、GB 等.我想知道我写的代码是否正确,是否可以简化.
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.
我写的函数如下:
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.
提前致谢
答
这里有一个更简单的方法:
Here's a simpler way of doing it:
private var _levels:Array = ['bytes', 'Kb', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
private function bytesToString(bytes:Number):String
{
var index:uint = Math.floor(Math.log(bytes)/Math.log(1024));
return (bytes/Math.pow(1024, index)).toFixed(2) + this._levels[index];
}
为了完整起见,我将它包含到了 yottabytes :)
I included it up to yottabytes for completeness :)