function humanFileSize($size)
{
if ($size >= 1073741824) {
$fileSize = round($size / 1024 / 1024 / 1024,1) . \'GB\';
} elseif ($size >= 1048576)
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") . "
"; ;