From ac691e01e56db625f838d3d548f3c28612614601 Mon Sep 17 00:00:00 2001 From: Benjamin Morel Date: Wed, 17 Jun 2015 00:40:31 +0200 Subject: [PATCH] Add BigDecimal::stripTrailingZeros() --- src/BigDecimal.php | 33 +++++++++++++++++++++++++++ tests/BigDecimalTest.php | 49 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/src/BigDecimal.php b/src/BigDecimal.php index 54ada0e..cc9168c 100644 --- a/src/BigDecimal.php +++ b/src/BigDecimal.php @@ -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. * diff --git a/tests/BigDecimalTest.php b/tests/BigDecimalTest.php index 4b12224..489f393 100644 --- a/tests/BigDecimalTest.php +++ b/tests/BigDecimalTest.php @@ -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 *