Created
November 25, 2014 23:18
-
-
Save Programie/f64c0937fe257b3fb1f6 to your computer and use it in GitHub Desktop.
Format bytes into a human readable format
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 | |
| /** | |
| * Format the given file size in bytes to a human readable format. | |
| * | |
| * @param int $size The file size to format in bytes | |
| * @param int $precision The optional number of decimal digits to round to | |
| * @return string The formatted file size (e.g. "4.7G") | |
| */ | |
| function formatFileSize($size, $precision = 1) | |
| { | |
| $units = array("B", "K", "M", "G", "T", "P", "E", "Z", "Y"); | |
| $useUnit = null; | |
| foreach ($units as $index => $unit) | |
| { | |
| if ($size < 1024) | |
| { | |
| $useUnit = $unit; | |
| break; | |
| } | |
| $size /= 1024; | |
| } | |
| if ($useUnit == null) | |
| { | |
| $useUnit = end($units); | |
| } | |
| return round($size, $precision) . $useUnit; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment