Skip to content

Commit

Permalink
fix(NumberFormatter): round number before format, correct behavior fo…
Browse files Browse the repository at this point in the history
…r ZeroClear::DECIMALS_EMPTY
  • Loading branch information
h4kuna committed Feb 14, 2024
1 parent 4bcb723 commit 96216f3
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
6 changes: 2 additions & 4 deletions src/Number/Formatters/NumberFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,10 @@ public function __construct(
}


private function initRoundCallback(null|int|callable $round): ?callable
private function initRoundCallback(null|int|callable $round): callable
{
if ($this->decimals < 0 && $round === null) {
if ($round === null || $round === Round::RESET) {
return Round::create();
} elseif ($round === null || $round === Round::RESET) {
return null;
} elseif (is_int($round)) {
return Round::create($round);
}
Expand Down
5 changes: 3 additions & 2 deletions src/Number/NumberFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ public static function unit(
if ($isZero && ($isNumeric === false || $zeroIsEmpty === true)) {
$formatted = $emptyValue === Space::AS_NULL ? '' : $emptyValue;
} else {
if ($zeroClear === ZeroClear::DECIMALS_EMPTY && $decimals > 0 && ((int) $castNumber) == $castNumber) {
$castNumber = ($roundCallback ?? Round::create())($castNumber, $decimals);
if (($zeroClear === ZeroClear::DECIMALS_EMPTY && $decimals > 0 && ((int) $castNumber) == $castNumber) || $decimals < 0) {
$decimals = 0;
}

$formatted = self::base($castNumber, $decimals, $decimalPoint, $thousandsSeparator, $roundCallback);
$formatted = self::base($castNumber, $decimals, $decimalPoint, $thousandsSeparator);

if ($zeroClear === ZeroClear::DECIMALS && $decimals > 0) {
$formatted = self::zeroClear($formatted, $decimalPoint);
Expand Down
5 changes: 5 additions & 0 deletions tests/src/Number/Formatters/NumberFormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,11 @@ protected function provideFormat(): array
'0,10',
0.1,
],
[
['zeroClear' => ZeroClear::DECIMALS_EMPTY, 'decimals' => 1],
'1',
0.99,
],
];
}

Expand Down

0 comments on commit 96216f3

Please sign in to comment.