diff --git a/src/Illuminate/Support/Number.php b/src/Illuminate/Support/Number.php index a101e903beb3..fbd3edc38691 100644 --- a/src/Illuminate/Support/Number.php +++ b/src/Illuminate/Support/Number.php @@ -208,6 +208,19 @@ protected static function summarize(int|float $number, int $precision = 0, ?int return trim(sprintf('%s%s', static::format($number, $precision, $maxPrecision), $units[$displayExponent] ?? '')); } + /** + * Clamp the given number between the given minimum and maximum. + * + * @param int|float $number + * @param int|float $min + * @param int|float $max + * @return int|float + */ + public static function clamp(int|float $number, int|float $min, int|float $max) + { + return min(max($number, $min), $max); + } + /** * Execute the given callback using the given locale. * diff --git a/tests/Support/SupportNumberTest.php b/tests/Support/SupportNumberTest.php index 67644fdcb209..ef1e619081f2 100644 --- a/tests/Support/SupportNumberTest.php +++ b/tests/Support/SupportNumberTest.php @@ -157,6 +157,15 @@ public function testBytesToHuman() $this->assertSame('1,024 YB', Number::fileSize(1024 ** 9)); } + public function testClamp() + { + $this->assertSame(2, Number::clamp(1, 2, 3)); + $this->assertSame(3, Number::clamp(5, 2, 3)); + $this->assertSame(5, Number::clamp(5, 1, 10)); + $this->assertSame(4.5, Number::clamp(4.5, 1, 10)); + $this->assertSame(1, Number::clamp(-10, 1, 5)); + } + public function testToHuman() { $this->assertSame('1', Number::forHumans(1));