From b440f8d3d8cc60ed97ee389f9efbd1f1501d461e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20Rub=C3=A9l?= Date: Thu, 27 Jul 2023 15:36:26 +0200 Subject: [PATCH] Add grouping and decimal separators (#31) ## About Adds the ability to set the grouping and decimal separators. --- --- src/Collection/LocaleNumberFormatter.php | 12 ++++++++++++ tests/LocaleNumberFormatterTest.php | 16 ++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/Collection/LocaleNumberFormatter.php b/src/Collection/LocaleNumberFormatter.php index 4477bce..4e48d1d 100644 --- a/src/Collection/LocaleNumberFormatter.php +++ b/src/Collection/LocaleNumberFormatter.php @@ -21,6 +21,8 @@ class LocaleNumberFormatter implements Formatter * @param int $style * @param string|null $pattern * @param int $fraction_digits + * @param string|null $grouping_separator + * @param string|null $decimal_separator */ public function __construct( public int|float|string|null $number = null, @@ -28,6 +30,8 @@ public function __construct( public int $style = NumberFormatter::DECIMAL, public ?string $pattern = null, public int $fraction_digits = 2, + public ?string $grouping_separator = null, + public ?string $decimal_separator = null, ) { } @@ -44,6 +48,14 @@ public function format(Collection $items): string|false $this->formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, $this->fraction_digits); + if ($this->grouping_separator) { + $this->formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $this->grouping_separator); + } + + if ($this->decimal_separator) { + $this->formatter->setSymbol(NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $this->decimal_separator); + } + return $this->formatter->format( (float) $this->number ); diff --git a/tests/LocaleNumberFormatterTest.php b/tests/LocaleNumberFormatterTest.php index c043321..8fe1bee 100644 --- a/tests/LocaleNumberFormatterTest.php +++ b/tests/LocaleNumberFormatterTest.php @@ -198,4 +198,20 @@ public function testCanExtendLocaleNumberFormatter() $this->assertEquals('10 000,56', $result); } + + /** @test */ + public function testCanSetGroupingAndDecimalSeparatorUsingExtend() + { + $this->app->extend(LocaleNumberFormatter::class, function (LocaleNumberFormatter $formatter) { + $formatter->locale = 'en'; + $formatter->grouping_separator = '-'; + $formatter->decimal_separator = ','; + + return $formatter; + }); + + $result = format(LocaleNumberFormatter::class, 10000.5550); + + $this->assertEquals('10-000,56', $result); + } }