Skip to content

Commit

Permalink
Fix negative numbers not supported by toString()
Browse files Browse the repository at this point in the history
  • Loading branch information
BenMorel committed Jun 7, 2015
1 parent de917b9 commit 2c35d6f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/BigInteger.php
Original file line number Diff line number Diff line change
Expand Up @@ -532,8 +532,6 @@ public function toInteger()
}

/**
* @todo test with negative numbers, probably broken
*
* Returns a string representation of this number in the given base.
*
* @param integer $base
Expand All @@ -559,6 +557,12 @@ public function toString($base)
$calc = Calculator::get();

$value = $this->value;
$negative = ($value[0] === '-');

if ($negative) {
$value = substr($value, 1);
}

$base = (string) $base;
$result = '';

Expand All @@ -569,6 +573,10 @@ public function toString($base)
$result .= $dictionary[$remainder];
}

if ($negative) {
$result .= '-';
}

return strrev($result);
}

Expand Down
1 change: 1 addition & 0 deletions tests/BigIntegerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1483,6 +1483,7 @@ public function testToIntegerPositiveOverflowThrowsException()
public function testToString($number, $base, $expected)
{
$this->assertSame($expected, BigInteger::parse($number)->toString($base));
$this->assertSame('-' . $expected, BigInteger::parse('-' . $number)->toString($base));
}

/**
Expand Down

0 comments on commit 2c35d6f

Please sign in to comment.