單位換算
/**
* @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));
運行結果: