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

前端 未结 2 2011
梦如初夏
梦如初夏 2021-01-06 00:49

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

相关标签:
2条回答
  • 2021-01-06 01:43

    @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);
    }
    
    0 讨论(0)
  • 2021-01-06 01:45

    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 :)

    0 讨论(0)
提交回复
热议问题