human readable file size

前端 未结 11 2247
梦毁少年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条回答
  •  梦毁少年i
    2020-12-25 11:32

    To expand on Vaidas' answer, here's how you should do it to account for the new IEC standards:

    function human_readable_bytes($bytes, $decimals = 2, $system = 'binary')
    {
        $mod = ($system === 'binary') ? 1024 : 1000;
    
        $units = array(
            'binary' => array(
                'B',
                'KiB',
                'MiB',
                'GiB',
                'TiB',
                'PiB',
                'EiB',
                'ZiB',
                'YiB',
            ),
            'metric' => array(
                'B',
                'kB',
                'MB',
                'GB',
                'TB',
                'PB',
                'EB',
                'ZB',
                'YB',
            ),
        );
    
        $factor = floor((strlen($bytes) - 1) / 3);
    
        return sprintf("%.{$decimals}f%s", $bytes / pow($mod, $factor), $units[$system][$factor]);
    }
    

    Technically, according to the specifications for storage devices and such you should use the metric system as default (that's why Google converter shows kB -> MB as mod 1000 instead of 1024).

提交回复
热议问题