diff --git a/src/Illuminate/Support/Number.php b/src/Illuminate/Support/Number.php index 11035b0b9827..d63884940021 100644 --- a/src/Illuminate/Support/Number.php +++ b/src/Illuminate/Support/Number.php @@ -216,6 +216,27 @@ public static function fileSize(int|float $bytes, int $precision = 0, ?int $maxP return sprintf('%s %s', static::format($bytes, $precision, $maxPrecision), $units[$i]); } + /** + * Convert the given number to its bit rate equivalent. + * + * @param int|float $bits + * @param int $precision + * @param int|null $maxPrecision + * @return string + */ + public static function bitRate(int|float $bits, int $precision = 0, ?int $maxPrecision = null) + { + $units = ['bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps', 'Pbps', 'Ebps', 'Zbps', 'Ybps']; + + $unitCount = count($units); + + for ($i = 0; ($bits / 1000) > 0.9 && ($i < $unitCount - 1); $i++) { + $bits /= 1000; + } + + return sprintf('%s %s', static::format($bits, $precision, $maxPrecision), $units[$i]); + } + /** * Convert the number to its human-readable equivalent. * diff --git a/tests/Support/SupportNumberTest.php b/tests/Support/SupportNumberTest.php index 7f7de7f3f1a2..0cdb6c5afb78 100644 --- a/tests/Support/SupportNumberTest.php +++ b/tests/Support/SupportNumberTest.php @@ -188,6 +188,29 @@ public function testBytesToHuman() $this->assertSame('1,024 YB', Number::fileSize(1024 ** 9)); } + public function testBitRate() + { + $this->assertSame('0 bps', Number::bitRate(0)); + $this->assertSame('0.00 bps', Number::bitRate(0, precision: 2)); + $this->assertSame('1 bps', Number::bitRate(1)); + $this->assertSame('900 bps', Number::bitRate(900)); + $this->assertSame('1 Kbps', Number::bitRate(1000)); + $this->assertSame('2 Kbps', Number::bitRate(2000)); + $this->assertSame('2.00 Kbps', Number::bitRate(2000, precision: 2)); + $this->assertSame('1.25 Kbps', Number::bitRate(1250, precision: 2)); + $this->assertSame('1.235 Kbps', Number::bitRate(1234.56789, maxPrecision: 3)); + $this->assertSame('1.235 Kbps', Number::bitRate(1234.56789, 3)); + $this->assertSame('1 Mbps', Number::bitRate(1000 * 1000)); + $this->assertSame('1 Gbps', Number::bitRate(1000 * 1000 * 1000)); + $this->assertSame('5 Gbps', Number::bitRate(1000 * 1000 * 1000 * 5)); + $this->assertSame('10 Tbps', Number::bitRate((1000 ** 4) * 10)); + $this->assertSame('10 Pbps', Number::bitRate((1000 ** 5) * 10)); + $this->assertSame('1 Ebps', Number::bitRate(1000 ** 6)); + $this->assertSame('1 Zbps', Number::bitRate(1000 ** 7)); + $this->assertSame('1 Ybps', Number::bitRate(1000 ** 8)); + $this->assertSame('1,000 Ybps', Number::bitRate(1000 ** 9)); + } + public function testClamp() { $this->assertSame(2, Number::clamp(1, 2, 3));