From d9c328ce85b28b01823dcb94b0ba99cb1e3ea0f1 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Fri, 17 Nov 2023 10:34:55 -0600 Subject: [PATCH] add spell and ordinal --- src/Illuminate/Support/Number.php | 32 +++++++++++++++++++++++++++++ tests/Support/SupportNumberTest.php | 20 ++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/Illuminate/Support/Number.php b/src/Illuminate/Support/Number.php index cca9795ff0e6..6053f0a66f6e 100644 --- a/src/Illuminate/Support/Number.php +++ b/src/Illuminate/Support/Number.php @@ -41,6 +41,38 @@ public static function format(int|float $number, ?int $precision = null, ?int $m return $formatter->format($number); } + /** + * Spell out the given number in the given locale. + * + * @param int|float $number + * @param ?string $locale + * @return string + */ + public static function spell(int|float $number, ?string $locale = null) + { + static::ensureIntlExtensionIsInstalled(); + + $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::SPELLOUT); + + return $formatter->format($number); + } + + /** + * Convert the given number to ordinal form. + * + * @param int|float $number + * @param ?string $locale + * @return string + */ + public static function ordinal(int|float $number, ?string $locale = null) + { + static::ensureIntlExtensionIsInstalled(); + + $formatter = new NumberFormatter($locale ?? static::$locale, NumberFormatter::ORDINAL); + + return $formatter->format($number); + } + /** * Convert the given number to its percentage equivalent. * diff --git a/tests/Support/SupportNumberTest.php b/tests/Support/SupportNumberTest.php index 58470731e70b..e758ecabdede 100644 --- a/tests/Support/SupportNumberTest.php +++ b/tests/Support/SupportNumberTest.php @@ -62,6 +62,26 @@ public function testFormatWithAppLocale() Number::useLocale('en'); } + public function testSpellout() + { + $this->assertSame('ten', Number::spell(10)); + $this->assertSame('one point two', Number::spell(1.2)); + } + + public function testSpelloutWithLocale() + { + $this->needsIntlExtension(); + + $this->assertSame('trois', Number::spell(3, 'fr')); + } + + public function testOrdinal() + { + $this->assertSame('1st', Number::ordinal(1)); + $this->assertSame('2nd', Number::ordinal(2)); + $this->assertSame('3rd', Number::ordinal(3)); + } + public function testToPercent() { $this->needsIntlExtension();