Home > Article > Backend Development > How to Format Bytes into Human-Readable Units with Precision?
Formatting Bytes with Precision
In various scenarios, it becomes necessary to format byte values into human-readable units such as kilobytes, megabytes, and gigabytes. For example, displaying file sizes on web pages requires formatting bytes to the appropriate unit.
Solution: Using a Format Function
One effective solution is to employ a formatting function that takes bytes as input and returns the formatted string. Here's an example PHP function that achieves this:
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); // Uncomment one of the following alternatives // $bytes /= pow(1024, $pow); // $bytes /= (1 << (10 * $pow)); return round($bytes, $precision) . $units[$pow]; }
Explanation
This function takes two parameters:
The function uses an array $units to represent the units (bytes, kilobytes, megabytes, gigabytes, and terabytes). It calculates the power $pow representing the appropriate unit by dividing the logarithm of $bytes by the logarithm of 1024. The maximum power is capped at the highest unit in the array.
The function then divides the byte value by the appropriate power to convert it to the desired unit. Finally, it rounds the value to the specified precision and appends the corresponding unit from the $units array.
For instance, if $bytes is 5,222,937, the function would format it as "5.01 MB".
The above is the detailed content of How to Format Bytes into Human-Readable Units with Precision?. For more information, please follow other related articles on the PHP Chinese website!