Skip to content

Commit 06b6921

Browse files
jbrooksukStyleCIBottaylorotwell
authored
[10.x] Add Number::clamp (#49512)
* Add Number::clamp * Apply fixes from StyleCI * Update Number.php --------- Co-authored-by: StyleCI Bot <[email protected]> Co-authored-by: Taylor Otwell <[email protected]>
1 parent 13f7830 commit 06b6921

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/Illuminate/Support/Number.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,19 @@ protected static function summarize(int|float $number, int $precision = 0, ?int
208208
return trim(sprintf('%s%s', static::format($number, $precision, $maxPrecision), $units[$displayExponent] ?? ''));
209209
}
210210

211+
/**
212+
* Clamp the given number between the given minimum and maximum.
213+
*
214+
* @param int|float $number
215+
* @param int|float $min
216+
* @param int|float $max
217+
* @return int|float
218+
*/
219+
public static function clamp(int|float $number, int|float $min, int|float $max)
220+
{
221+
return min(max($number, $min), $max);
222+
}
223+
211224
/**
212225
* Execute the given callback using the given locale.
213226
*

tests/Support/SupportNumberTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,15 @@ public function testBytesToHuman()
157157
$this->assertSame('1,024 YB', Number::fileSize(1024 ** 9));
158158
}
159159

160+
public function testClamp()
161+
{
162+
$this->assertSame(2, Number::clamp(1, 2, 3));
163+
$this->assertSame(3, Number::clamp(5, 2, 3));
164+
$this->assertSame(5, Number::clamp(5, 1, 10));
165+
$this->assertSame(4.5, Number::clamp(4.5, 1, 10));
166+
$this->assertSame(1, Number::clamp(-10, 1, 5));
167+
}
168+
160169
public function testToHuman()
161170
{
162171
$this->assertSame('1', Number::forHumans(1));

0 commit comments

Comments
 (0)