Skip to content

Commit

Permalink
Add grouping and decimal separators (#31)
Browse files Browse the repository at this point in the history
## About

Adds the ability to set the grouping and decimal separators.

---
  • Loading branch information
michael-rubel authored Jul 27, 2023
1 parent 796a489 commit b440f8d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/Collection/LocaleNumberFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,17 @@ 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,
public ?string $locale = null,
public int $style = NumberFormatter::DECIMAL,
public ?string $pattern = null,
public int $fraction_digits = 2,
public ?string $grouping_separator = null,
public ?string $decimal_separator = null,
) {
}

Expand All @@ -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
);
Expand Down
16 changes: 16 additions & 0 deletions tests/LocaleNumberFormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit b440f8d

Please sign in to comment.