Skip to content

Instantly share code, notes, and snippets.

@Thinkscape
Last active December 19, 2015 23:59
Show Gist options
  • Select an option

  • Save Thinkscape/6037931 to your computer and use it in GitHub Desktop.

Select an option

Save Thinkscape/6037931 to your computer and use it in GitHub Desktop.
Converts int bytes to a highest, rounded, multiplication that is IEC compliant.
<?php
/**
* Converts int bytes to a highest, rounded, multiplication that is IEC compliant.
*
* @link https://en.wikipedia.org/wiki/Binary_prefix
*
* @param int $size Number of bytes to convert
* @param int $precision Rounding precision (defaults to 0)
* @return string Highest rounded multiplication with IEC suffix
*/
function bytesToString($size, $precision = 0) {
if ($size > 1125899906842624) {
$size /= 1125899906842624;
$suffix = 'PiB';
} elseif ($size > 1099511627776) {
$size /= 1099511627776;
$suffix = 'TiB';
} elseif ($size > 1073741824) {
$size /= 1073741824;
$suffix = 'GiB';
} elseif ($size > 1048576) {
$size /= 1048576;
$suffix = 'MiB';
} elseif ($size > 1024) {
$size /= 1024;
$suffix = 'KiB';
} else {
$suffix = 'B';
}
return round($size, $precision) . ' ' . $suffix;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment