Created
October 26, 2017 08:58
-
-
Save sentenza/27e3a5d8f303980756cf56a24df2487b to your computer and use it in GitHub Desktop.
Bytes formatting (KB, MB, GB)
This file contains 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 | |
/** | |
* Format an amount of bytes using a SI metric conversion | |
* | |
* Note: 1024 to express the format in KiB, MiB | |
* | |
* @author Alfredo Torre <alfredo@dubishere.com> | |
* @see https://en.wikipedia.org/wiki/Kibibyte | |
* @param string/int $pBytes | |
* @param int $piPrecision | |
* @return string The formatted bytes dimension | |
*/ | |
private function formatBytes($pBytes, $piPrecision = 2) { | |
$iBytes = max((int) $pBytes, 0); | |
$aUnits = array('B', 'KB', 'MB', 'GB', 'TB'); | |
$iBase = log($iBytes, 1000); | |
$iFormatted = round(pow(1000, $iBase - floor($iBase)), $piPrecision); | |
return sprintf('%s %s', $iFormatted, $aUnits[floor($iBase)]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment