From 8151a80ac347836dafa343503f37e92d330cad9f Mon Sep 17 00:00:00 2001 From: Caen De Silva Date: Wed, 1 Nov 2023 18:47:07 +0100 Subject: [PATCH] Add a `Number::toCurrency()` helper --- src/Illuminate/Support/Number.php | 17 ++++++++++++++++ tests/Support/SupportNumberTest.php | 30 +++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/src/Illuminate/Support/Number.php b/src/Illuminate/Support/Number.php index 986766b4dcc1..ca4f40e15d9b 100644 --- a/src/Illuminate/Support/Number.php +++ b/src/Illuminate/Support/Number.php @@ -26,6 +26,23 @@ public static function toHuman($number, $locale = 'en') return $formatter->format($number); } + /** + * Format the number to a currency format. + * + * @param float|int $number + * @param string $currency + * @param string $locale + * @return false|string + */ + public static function toCurrency($number, $currency = 'USD', $locale = 'en') + { + static::needsIntlExtension(); + + $formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY); + + return $formatter->formatCurrency($number, $currency); + } + /** * Format the number of bytes to a human-readable string. * diff --git a/tests/Support/SupportNumberTest.php b/tests/Support/SupportNumberTest.php index 38fea02dd855..878a23c7e16f 100644 --- a/tests/Support/SupportNumberTest.php +++ b/tests/Support/SupportNumberTest.php @@ -45,6 +45,36 @@ public function testToHumanWithDifferentLocale() $this->assertSame('ett­hundra­tjugo­tre', Number::toHuman(123, 'sv')); } + public function testToCurrency() + { + $this->needsIntlExtension(); + + $this->assertSame('$0.00', Number::toCurrency(0)); + $this->assertSame('$1.00', Number::toCurrency(1)); + $this->assertSame('$10.00', Number::toCurrency(10)); + + $this->assertSame('€0.00', Number::toCurrency(0, 'EUR')); + $this->assertSame('€1.00', Number::toCurrency(1, 'EUR')); + $this->assertSame('€10.00', Number::toCurrency(10, 'EUR')); + + $this->assertSame('-$5.00', Number::toCurrency(-5)); + $this->assertSame('$5.00', Number::toCurrency(5.00)); + $this->assertSame('$5.32', Number::toCurrency(5.325)); + } + + public function testToCurrencyWithDifferentLocale() + { + $this->needsIntlExtension(); + + $this->assertSame('1,00 €', Number::toCurrency(1, 'EUR', 'de')); + $this->assertSame('1,00 $', Number::toCurrency(1, 'USD', 'de')); + $this->assertSame('1,00 £', Number::toCurrency(1, 'GBP', 'de')); + + $this->assertSame('123.456.789,12 $', Number::toCurrency(123456789.12345, 'USD', 'de')); + $this->assertSame('123.456.789,12 €', Number::toCurrency(123456789.12345, 'EUR', 'de')); + $this->assertSame('1 234,56 $US', Number::toCurrency(1234.56, 'USD', 'fr')); + } + public function testBytesToHuman() { $this->assertSame('0 B', Number::bytesToHuman(0));