字节单位数值转成以KB、MB、GB、TB为单位

<?php
/**
 * 字节单位数值转成以KB、MB、GB、TB为单位
 *
 * @param int $bytes 字节数
 * @param int $precision 保留多少位小数
 * @return string 新单位数值
 */
function bytes_format(int $bytes, int $precision = 2): string
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];

    $bytes = max($bytes, 0);

    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);

    $bytes /= 1024 ** $pow;

    return round($bytes, $precision) . $units[$pow];
}

$bytes = 64;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 64字节 ---> 64B

$bytes = 512;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 512字节 ---> 512B

$bytes = 1024;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 1024字节 ---> 1KB

$bytes = 262144;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 262144字节 ---> 256KB

$bytes = 524288;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 524288字节 ---> 512KB

$bytes = 1048576;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 1048576字节 ---> 1MB

$bytes = 1572864;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 1572864字节 ---> 1.5MB

$bytes = 2097152;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 2097152字节 ---> 2MB

$bytes = 5242880;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 5242880字节 ---> 5MB

$bytes = 10485760;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 10485760字节 ---> 10MB

$bytes = 536870912;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 536870912字节 ---> 512MB

$bytes = 1073741824;
echo "{$bytes}字节 ---> " . bytes_format($bytes) . PHP_EOL; // 1073741824字节 ---> 1GB

Copyright © 2024 码农人生. All Rights Reserved