Formatting Byte Values: Convert Bytes to Kilobytes, Megabytes, and Gigabytes
When storing file sizes in a database, it's often recorded as bytes. However, for user readability, it's more practical to display these values in more manageable units such as kilobytes, megabytes, and gigabytes.
To achieve this, we can employ a PHP script like the one below:
function formatBytes($bytes, $precision = 2) { $units = array('B', 'KB', 'MB', 'GB', 'TB'); $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $bytes /= (1 << (10 * $pow)); return round($bytes, $precision) . $units[$pow]; }
This function takes the byte value as an argument and returns a formatted string that represents the size in the appropriate unit. For example, if you pass "5445632" bytes as input, the function will return "5.2 MB".
The above is the detailed content of How to Convert Bytes to Kilobytes, Megabytes, and Gigabytes in PHP?. For more information, please follow other related articles on the PHP Chinese website!