human readable file size

前端 未结 11 2254
梦毁少年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:52

    You can modify your function to fullfil both your need to force a unit if given and adjust the precision.

    function humanFileSize($size, $precision = 1, $show = "")
    {
        $b = $size;
        $kb = round($size / 1024, $precision);
        $mb = round($kb / 1024, $precision);
        $gb = round($mb / 1024, $precision);
    
        if($kb == 0 || $show == "B") {
            return $b . " bytes";
        } else if($mb == 0 || $show == "KB") {
            return $kb . "KB";
        } else if($gb == 0 || $show == "MB") {
            return $mb . "MB";
        } else {
            return $gb . "GB";
        }
    }
    
    //Test with different values
    echo humanFileSize(1038) . "
    "; echo humanFileSize(103053, 0) . "
    "; echo humanFileSize(103053) . "
    "; echo humanFileSize(1030544553) . "
    "; echo humanFileSize(1030534053405, 2, "GB") . "
    "; ;

提交回复
热议问题