Skip to content

Instantly share code, notes, and snippets.

@paulofreitas
Created October 10, 2013 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulofreitas/6922365 to your computer and use it in GitHub Desktop.
Save paulofreitas/6922365 to your computer and use it in GitHub Desktop.
<?php
function formatSize($bytes, $force_unit = null, $format = null, $si = true)
{
// Format string
$format = ($format === null) ? '%01.2f %s' : (string) $format;
if (($si == false) || (strpos($force_unit, 'i') !== false)) {
// IEC prefixes (binary)
$units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
$mod = 1024;
} else {
// SI prefixes (decimal)
$units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
$mod = 1000;
}
// Determine unit to use
if (($power = array_search((string) $force_unit, $units)) === false) {
$power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0;
}
return sprintf($format, $bytes / pow($mod, $power), $units[$power]);
}
// Testing...
var_dump(formatSize(1048576 * 1.75)); // 1.84 MB
var_dump(formatSize(1048576 * 1.75, null, null, false)); // 1.75 MB
var_dump(formatSize(1048576 * 1.75, 'kB')); // 1835.01 kB
var_dump(formatSize(1048576 * 1.75, 'KiB')); // 1792.00 KiB
var_dump(formatSize(1048576 * 1.75, 'KiB', '%d %s')); // 1792 KiB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment