human readable file size

前端 未结 11 2308
梦毁少年i
梦毁少年i 2020-12-25 10:48
function humanFileSize($size)
{
    if ($size >= 1073741824) {
      $fileSize = round($size / 1024 / 1024 / 1024,1) . \'GB\';
    } elseif ($size >= 1048576)          


        
11条回答
  •  难免孤独
    2020-12-25 11:28

    This is how I use, it's clean and simple. Also can be used like this:

    public function getHumanReadableFilesize(int $bytes, int $dec = 2): string
    {
        $size   = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        $factor = floor((strlen($bytes) - 1) / 3);
    
        return sprintf("%.{$dec}f %s", ($bytes / (1024 ** $factor)), $size[$factor]);
    }
    

    Thanks @Márton Tamás for suggestion to add like comment.

提交回复
热议问题