Skip to content

Commit

Permalink
[10.x] Add a threshold parameter to the Number::spell helper (lar…
Browse files Browse the repository at this point in the history
…avel#49610)

* [10.x] Add a `threshold` parameter to the `Number::spell` helper

Adds a parameter to limit how high numbers are spelled out.

* Add docblock for the threshold parameter

* adjust logic

* formatting

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
2 people authored and fjarrett committed Jan 10, 2024
1 parent 39527e3 commit bb377f1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Illuminate/Support/Number.php
Expand Up @@ -46,12 +46,22 @@ public static function format(int|float $number, ?int $precision = null, ?int $m
*
* @param int|float $number
* @param string|null $locale
* @param int|null $after
* @param int|null $until
* @return string
*/
public static function spell(int|float $number, ?string $locale = null)
public static function spell(int|float $number, ?string $locale = null, ?int $after = null, ?int $until = null)
{
static::ensureIntlExtensionIsInstalled();

if (! is_null($after) && $number <= $after) {
return static::format($number, locale: $locale);
}

if (! is_null($until) && $number >= $until) {
return static::format($number, locale: $locale);
}

$formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::SPELLOUT);

return $formatter->format($number);
Expand Down
16 changes: 16 additions & 0 deletions tests/Support/SupportNumberTest.php
Expand Up @@ -77,6 +77,22 @@ public function testSpelloutWithLocale()
$this->assertSame('trois', Number::spell(3, 'fr'));
}

public function testSpelloutWithThreshold()
{
$this->needsIntlExtension();

$this->assertSame('9', Number::spell(9, after: 10));
$this->assertSame('10', Number::spell(10, after: 10));
$this->assertSame('eleven', Number::spell(11, after: 10));

$this->assertSame('nine', Number::spell(9, until: 10));
$this->assertSame('10', Number::spell(10, until: 10));
$this->assertSame('11', Number::spell(11, until: 10));

$this->assertSame('ten thousand', Number::spell(10000, until: 50000));
$this->assertSame('100,000', Number::spell(100000, until: 50000));
}

public function testOrdinal()
{
$this->assertSame('1st', Number::ordinal(1));
Expand Down

0 comments on commit bb377f1

Please sign in to comment.