ActionScript code to convert bytes to kb, mb, gb etc

…衆ロ難τιáo~ 提交于 2019-12-09 00:40:58

问题


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


回答1:


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];
}

I included it up to yottabytes for completeness :)




回答2:


@J_A_X has the best way to do this, however for the future, I suggest returning early when you find you have nested if...else...if statements like you have.

public static function formatFileSize(bytes:int):String
{
    if(bytes < 1024)
        return bytes + " bytes";

    bytes /= 1024;
    if(bytes < 1024)
        return bytes + " Kb";

    bytes /= 1024;
    if(bytes < 1024)
        return bytes + " Mb";

    bytes /= 1024;
    if(bytes < 1024)
        return bytes + " Gb";

    return String(bytes);
}


来源:https://stackoverflow.com/questions/5805826/actionscript-code-to-convert-bytes-to-kb-mb-gb-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!