动作code转换成字节,以KB,MB,GB等转换成、字节、动作、code

2023-09-09 21:23:32 作者:人生若只如初见、

我有一个效用函数,将在像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 :)