Skip to content

Commit

Permalink
Add BigDecimal::stripTrailingZeros()
Browse files Browse the repository at this point in the history
  • Loading branch information
BenMorel committed Jun 16, 2015
1 parent 0a8b269 commit ac691e0
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/BigDecimal.php
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,39 @@ public function withPointMovedRight($n)
return new BigDecimal($value, $scale);
}

/**
* Returns a copy of this BigDecimal with any trailing zeros removed from the fractional part.
*
* @return BigDecimal
*/
public function stripTrailingZeros()
{
if ($this->scale === 0) {
return $this;
}

$trimmedValue = rtrim($this->value, '0');

if ($trimmedValue === '') {
return new BigDecimal('0');
}

$trimmableZeros = strlen($this->value) - strlen($trimmedValue);

if ($trimmableZeros === 0) {
return $this;
}

if ($trimmableZeros > $this->scale) {
$trimmableZeros = $this->scale;
}

$value = substr($this->value, 0, -$trimmableZeros);
$scale = $this->scale - $trimmableZeros;

return new BigDecimal($value, $scale);
}

/**
* Returns the absolute value of this number.
*
Expand Down
49 changes: 49 additions & 0 deletions tests/BigDecimalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1534,6 +1534,55 @@ public function providerWithPointMovedRight()
];
}

/**
* @dataProvider providerStripTrailingZeros
*
* @param string $number The number to trim.
* @param string $expected The expected result.
*/
public function testStripTrailingZeros($number, $expected)
{
$actual = BigDecimal::of($number)->stripTrailingZeros();
$this->assertSame($expected, (string) $actual);
}

/**
* @return array
*/
public function providerStripTrailingZeros()
{
return [
['0', '0'],
['0.0', '0'],
['0.00', '0'],
['0.000', '0'],
['0.1', '0.1'],
['0.01', '0.01'],
['0.001', '0.001'],
['0.100', '0.1'],
['0.0100', '0.01'],
['0.00100', '0.001'],
['1', '1'],
['1.0', '1'],
['1.00', '1'],
['1.10', '1.1'],
['1.123000', '1.123'],
['10', '10'],
['10.0', '10'],
['10.00', '10'],
['10.10', '10.1'],
['10.01', '10.01'],
['10.010', '10.01'],
['100', '100'],
['100.0', '100'],
['100.00', '100'],
['100.01', '100.01'],
['100.10', '100.1'],
['100.010', '100.01'],
['100.100', '100.1'],
];
}

/**
* @dataProvider providerAbs
*
Expand Down

0 comments on commit ac691e0

Please sign in to comment.