Home  >  Article  >  Backend Development  >  How to Format Bytes into Human-Readable Units with Precision?

How to Format Bytes into Human-Readable Units with Precision?

Barbara Streisand
Barbara StreisandOriginal
2024-11-19 02:30:03674browse

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:

  • $bytes: The size of the file in bytes
  • $precision: The number of decimal places to display

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn