diff --git a/src/BigNumber.php b/src/BigNumber.php index 41e2c05..87784ec 100644 --- a/src/BigNumber.php +++ b/src/BigNumber.php @@ -14,6 +14,13 @@ interface BigNumber { public const AUTOMATIC_SCALE = null; + /** + * Converts the current BigNumber to its absolute value. + * + * @return BigNumber A new BigNumber representing the absolute value. + */ + public function absolute(): BigNumber; + /** * Adds the current BigNumber (augend) with another BigNumber (addend). * diff --git a/src/Internal/BigNumberBehavior.php b/src/Internal/BigNumberBehavior.php index 1a539aa..c765ec1 100644 --- a/src/Internal/BigNumberBehavior.php +++ b/src/Internal/BigNumberBehavior.php @@ -27,6 +27,11 @@ abstract public static function fromFloat(float $value, ?int $scale = BigNumber: abstract public static function fromString(string $value, ?int $scale = BigNumber::AUTOMATIC_SCALE): BigNumber; + public function absolute(): BigNumber + { + return static::fromString(value: (string)abs((float)$this->number->value)); + } + public function add(BigNumber $addend): BigNumber { $result = $this->mathOperations->add(augend: $this, addend: $addend); diff --git a/tests/BigNumberTest.php b/tests/BigNumberTest.php index 812ca59..382998b 100644 --- a/tests/BigNumberTest.php +++ b/tests/BigNumberTest.php @@ -11,6 +11,23 @@ final class BigNumberTest extends TestCase { + public function testAbsolute(): void + { + /** @Given a BigNumber instance */ + $negativeValue = -10.155; + $number = LargeNumber::fromFloat(value: $negativeValue); + + /** @When calling the absolute method */ + $actual = $number->absolute(); + + /** @Then the result should be an instance of BigNumber */ + self::assertInstanceOf(BigNumber::class, $actual); + + /** @And the value should be the absolute value of the negative number */ + self::assertSame(abs($negativeValue), $actual->toFloat()); + self::assertSame(sprintf('%s', abs($negativeValue)), $actual->toString()); + } + #[DataProvider('providerForTestAdd')] public function testAdd(int $scale, mixed $value, mixed $other, array $expected): void {