Skip to content

Instantly share code, notes, and snippets.

@sentenza
Created October 26, 2017 08:58
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 sentenza/27e3a5d8f303980756cf56a24df2487b to your computer and use it in GitHub Desktop.
Save sentenza/27e3a5d8f303980756cf56a24df2487b to your computer and use it in GitHub Desktop.
Bytes formatting (KB, MB, GB)
<?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