Skip to content

Commit

Permalink
Add MathUtils::formatBytes
Browse files Browse the repository at this point in the history
  • Loading branch information
Louis Fortunier committed Jan 11, 2024
1 parent 04d397c commit 564d7ea
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
CHANGELOG for 1.x
===================
## v1.0.2 - (2024-01-11)

### Added

- `MathUtils::formatBytes` : Transform byte into readable format

## v1.0.1 - (2024-01-05)

### Added
Expand Down
12 changes: 12 additions & 0 deletions src/Utils/MathUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,16 @@ public static function calculatePercentage(?float $partial, float $total, ?int $

return $roundPrecision === null ? $toReturn : round($toReturn, $roundPrecision);
}

/**
* Convert and Transform byte into readable format
*/
public static function formatBytes(float $size, int $precision = 2): string
{
$base = log($size, 1024);
$suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];

$floor = floor($base);
return round(pow(1024, $base - $floor), $precision) . ' ' . $suffixes[$floor];
}
}
30 changes: 30 additions & 0 deletions tests/Utils/MathUtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,34 @@ public function getPercentProvider(): array
'safe_calc_percent_divided_by_zero' => [0, 10, 0, 1],
];
}

/**
* @dataProvider formatBytesProvider
*/
public function testFormatBytes(string $expected, float $size, ?int $roundPrecision = null): void
{
if ($roundPrecision === null) {
$this->assertEquals($expected, MathUtils::formatBytes($size));
} else {
$this->assertEquals($expected, MathUtils::formatBytes($size, $roundPrecision));
}
}

public function formatBytesProvider(): array
{
return [
'999 B' => [
// expected
'999 B',
// size
999,
// precision
null,
],
'1.26 KB' => ['1.26 KB', 1290, null],
'536.918 MB' => ['536.918 MB', 562999000, 3],
'880 GB' => ['880 GB', 945000000000, 0],
'382.86 TB' => ['382.86 TB', 420956000000000, 2],
];
}
}

0 comments on commit 564d7ea

Please sign in to comment.