Skip to content

Commit 61a51c0

Browse files
committed
[FIX] Refactor nicesize() via ISO standard.
1 parent bfead93 commit 61a51c0

1 file changed

Lines changed: 20 additions & 10 deletions

File tree

core/functions/helper.php

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -121,21 +121,31 @@ function is_cli()
121121

122122
if (!function_exists('nicesize')) {
123123
/**
124-
* @param $size
125-
* @return string
124+
* Format file size in human-readable format.
125+
*
126+
* Converts bytes to appropriate unit (B, KB, MB, GB, TB) with proper rounding.
127+
* Uses modern ISO/IEC 80000 standard formatting with uppercase units.
128+
*
129+
* @param int $size File size in bytes
130+
* @return string Formatted file size with unit
131+
*
132+
* @example
133+
* nicesize(1024); // "1 KB"
134+
* nicesize(1048576); // "1 MB"
135+
* nicesize(1536); // "1.5 KB"
136+
* nicesize(0); // "0 B"
126137
*/
127138
function nicesize($size)
128139
{
129-
$sizes = array('Tb' => 1099511627776, 'Gb' => 1073741824, 'Mb' => 1048576, 'Kb' => 1024, 'b' => 1);
130-
$precisions = count($sizes) - 1;
131-
foreach ($sizes as $unit => $bytes) {
132-
if ($size >= $bytes) {
133-
return number_format($size / $bytes, $precisions).' '.$unit;
134-
}
135-
$precisions--;
140+
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
141+
$unitIndex = 0;
142+
143+
while ($size >= 1024 && $unitIndex < count($units) - 1) {
144+
$size /= 1024;
145+
$unitIndex++;
136146
}
137147

138-
return '0 b';
148+
return round($size, 2) . ' ' . $units[$unitIndex];
139149
}
140150
}
141151

0 commit comments

Comments
 (0)