php 文件内大小单位转换
程序员文章站
2022-07-14 07:59:54
...
class unit {
private static $units = [
'0' => 'B',
'1' => 'KB',
'2' => 'MB',
'3' => 'GB',
'4' => 'TB',
'5' => 'PB'
];
//put your code here
public static function getUnit(int $size): string {
if ($size < 1) {
return '0B';
} elseif ($size < 1024) {
return $size . 'B';
}
for ($i = 0; $size >= 1024 && $i < 5; $i++) {
$size /= 1024;
}
return round($size, 2) . self::$units[$i];
}
public static function getSize(int $size, string $unit): int {
if (!in_array($unit, self::$units)) {
return $size;
}
$units = array_flip(self::$units);
return $size * pow(1024, $units[$unit]);
}
}