本文介绍了动作code转换成字节,以KB,MB,GB等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个效用函数,将在像Windows资源管理器,即以适当的形式显示文件大小;将其转换为最接近的KB,MB,GB等。我想知道,如果code,我写的是正确的,如果它可以变得简单。
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 :)
这篇关于动作code转换成字节,以KB,MB,GB等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!