PrettySize()
From Lankyland
prettySize()
Contents |
What it does
Pretty Size takes a file size in bytes and returns a Nice value in either Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Petabytes or Exabytes
Given that not many systems will be up to Terabytes, Petabytes or Exabytes you can chop off those areas and modify the last else maths to reflect your largest expected file size. I have only included them as I intend to build a file server that will be capable of storing > 5 Terabytes.
The Code
function prettySize($size)
{
if($size<1024) //bytes
{
return $size." bytes";
}
else if($size<(1024*1024)) //kilobytes
{
$size=round($size/1024,2);
return $size." Kb";
}
else if($size<(1024*1024*1024)) //megabytes
{
$size=round($size/(1024*1024),2);
return $size." MB";
}
else if($size<(1024*1024*1024*1024)) //gigabytes
{
$size=round($size/(1024*1024*1024),2);
return $size." Gb";
}
else if($size<(1024*1024*1024*1024*1024)) //terabytes
{
$size=round($size/(1024*1024*1024*1024),2);
return $size. " Tb";
}
else if($size<(1024*1024*1024*1024*1024*1024)) //petabytes
{
$size=round($size/(1024*1024*1024*1024*1024),2);
return $size. " Pb";
}
else //exabytes
{
$size=round($size/(1024*1024*1024*1024*1024*1024),2);
return $size. " Eb";
}
}
How it Works
Pass the function the size in bytes.
- Size is what the
$sizevalue type is - Minimum is the number of bytes that the
$sizevalue needs to be to be the Size type - Maximum is the number of bytes that the
$sizevalue needs to be less than to be the Size type - Divider is the value you need to the divide
$sizevalue by to get a nice rounded number to much the Append - Append is what we add after the Rounded value
| Size | Minimum | Maximum | Divider | Append |
| Bytes | 0 | 1023 | 1 | bytes |
| Kilobytes | 1024 | 1048575 | 1024 | Kb |
| Megabytes | 1048576 | 1073741823 | 1048576 | MB |
| Gigabytes | 1073741824 | 1099511627775 | 1073741824 | Gb |
| Terabytes | 1099511627776 | 1125899906842623 | 1099511627776 | Tb |
| Petabytes | 1125899906842624 | 1152921504606846976 | 1125899906842624 | Pb |
| Exabytes | 1152921504606846975 | ∞ | 1152921504606846976 | Eb |
Examples
<? echo prettySize('1000'); ?>returns: 1000 bytes<? echo prettySize('103482'); ?>returns: 101.06 Kb<? echo prettySize('1035988762'); ?>returns: 988 MB<? echo prettySize('98335642267'); ?>returns: 91.58GB<? echo prettySize('1649267447664'); ?>returns: 1.5 Tb

