PHP 字節文件轉換單位 (Byte, KB, MB, GB, TB)

單位換算

/**
 * @param $byteFile 文件字節大小
 * @param string $unit 9216字節轉爲 9.000 KB,可選擇 [KB, MB, GB, TB]
 * @param int $float 9.000 默認近似值3位
 * @return string 9.000 KB
 * 默認轉換爲可能性最大的單位 9216 = 9.000 KB
 */
function file_convert_unit($byteFile, $unit = 'TB', $float = 3)
{
    // 順序: 從小到大添加單位,即可換算 [ 'GB', 'TB', '*****']
    $units = ['Byte', 'KB', 'MB', 'GB', 'TB'];
    list ($p, $unit) = [0, ucfirst($unit)];

    while ($byteFile > 1024 && $p < (count($units) - 2)) {
        if (hash_equals($units[$p], $unit) || hash_equals($unit, 'Byte')) {
            break;
        }

        $p++;
        $byteFile /= 1024;
    }

    return sprintf("%0.{$float}f %s", $byteFile, $units[$p]);
}

// 文件字節大小
$byteFile = 5745669164;

// 9216 Bytes =  9.000 KB
print("$byteFile Byte = " . file_convert_unit($byteFile, 'GB', 2));



運行結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章