Created
October 10, 2013 17:35
-
-
Save paulofreitas/6922365 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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