Skip to content

Commit

Permalink
feat: Adds an absolute method to return the absolute value of a BigNu…
Browse files Browse the repository at this point in the history
…mber instance.
  • Loading branch information
gustavofreze committed Oct 31, 2024
1 parent 5819053 commit c350fb3
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/BigNumber.php
Original file line number Diff line number Diff line change
Expand Up @@ -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).
*
Expand Down
5 changes: 5 additions & 0 deletions src/Internal/BigNumberBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
17 changes: 17 additions & 0 deletions tests/BigNumberTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down

0 comments on commit c350fb3

Please sign in to comment.