Skip to content

Commit

Permalink
[10.x] Add Number::clamp (#49512)
Browse files Browse the repository at this point in the history
* Add Number::clamp

* Apply fixes from StyleCI

* Update Number.php

---------

Co-authored-by: StyleCI Bot <[email protected]>
Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
3 people authored Dec 29, 2023
1 parent 13f7830 commit 06b6921
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Illuminate/Support/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/Support/SupportNumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down

0 comments on commit 06b6921

Please sign in to comment.