<?php
/**
* 格式化位元組數為人類可讀字串
* @param int|float $bytes 位元組數
* @param int $decimals 小數位數(預設 2)
* @return string 如 19.71 MB
*/
function format_bytes($bytes, $decimals = 2) {
if ($bytes < 0) return '0 B';
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$factor = floor((strlen((string)$bytes) - 1) / 3); // 以 1024 為基底的冪次
$factor = min($factor, count($units) - 1);
return sprintf("%.*f %s", $decimals, $bytes / (1024 ** $factor), $units[$factor]);
}
// 遞歸版(教學用)
function format_bytes_recursive($bytes, $times = 0) {
if ($bytes >= 1024) {
return format_bytes_recursive($bytes / 1024, $times + 1);
}
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
return sprintf('%.2f %s', $bytes, $units[$times]);
}
<?php
echo format_bytes(20667564); // 19.71 MB
echo format_bytes(1024); // 1.00 KB
echo format_bytes(1073741824); // 1.00 GB
echo format_bytes(123); // 123.00 B
echo format_bytes(0); // 0.00 B
echo format_bytes(1234567890123); // 1.12 TB
| 單位 | 全名 | 倍數 (1024^n) | 約略十進位 |
|---|---|---|---|
| B | Byte | 1024^0 | 1 |
| KB | Kilobyte | 1024^1 | 1,024 |
| MB | Megabyte | 1024^2 | 1,048,576 |
| GB | Gigabyte | 1024^3 | 1,073,741,824 |
| TB | Terabyte | 1024^4 | 1,099,511,627,776 |
| PB | Petabyte | 1024^5 | 1.13e15 |
| EB | Exabyte | 1024^6 | 1.15e18 |
| ZB | Zettabyte | 1024^7 | 1.18e21 |
| YB | Yottabyte | 1024^8 | 1.21e24 |
0 B 或拋出異常。function format_bits($bits, $decimals = 2) {
return format_bytes($bits / 8, $decimals) . ' (bits)';
}
一個 format_bytes() 函數即可滿足 99% 檔案大小顯示需求。遞歸版適合教學理解遞歸與單位遞增邏輯;非遞歸版效能更好、程式碼更簡潔。記得處理邊界值(0、負數、超大數)與單位制統一(1024)。