Skip to content

Commit

Permalink
Add a Number::bytesToHuman() helper
Browse files Browse the repository at this point in the history
Ports #48827 into the new `Number` utility class
  • Loading branch information
caendesilva committed Oct 28, 2023
1 parent b5fb4a9 commit fb0e6ce
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
18 changes: 17 additions & 1 deletion src/Illuminate/Support/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,21 @@ class Number
{
use Macroable;

//
/**
* Format the number of bytes to a human-readable string.
*
* @param int $bytes
* @param int $precision
* @return string
*/
public static function bytesToHuman($bytes, $precision = 2)
{
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

for ($i = 0; ($bytes / 1024) > 0.9 && ($i < count($units) - 1); $i++) {
$bytes /= 1024;
}

return sprintf('%s %s', round($bytes, $precision), $units[$i]);
}
}
16 changes: 15 additions & 1 deletion tests/Support/SupportNumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,19 @@

class SupportNumberTest extends TestCase
{
//
public function testBytesToHuman()
{
$this->assertSame('0 B', Number::bytesToHuman(0));
$this->assertSame('1 B', Number::bytesToHuman(1));
$this->assertSame('1 KB', Number::bytesToHuman(1024));
$this->assertSame('2 KB', Number::bytesToHuman(2048));
$this->assertSame('1.23 KB', Number::bytesToHuman(1264));
$this->assertSame('1.234 KB', Number::bytesToHuman(1264, 3));
$this->assertSame('5 GB', Number::bytesToHuman(1024 * 1024 * 1024 * 5));
$this->assertSame('10 TB', Number::bytesToHuman((1024 ** 4) * 10));
$this->assertSame('10 PB', Number::bytesToHuman((1024 ** 5) * 10));
$this->assertSame('1 ZB', Number::bytesToHuman(1024 ** 7));
$this->assertSame('1 YB', Number::bytesToHuman(1024 ** 8));
$this->assertSame('1024 YB', Number::bytesToHuman(1024 ** 9));
}
}

0 comments on commit fb0e6ce

Please sign in to comment.