Skip to content
This repository has been archived by the owner on Dec 27, 2023. It is now read-only.

Commit

Permalink
Fix of the rounding error for negative numbers.
Browse files Browse the repository at this point in the history
  • Loading branch information
codisart committed Apr 2, 2015
1 parent d47cf15 commit a9a28af
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Decimal.php
Original file line number Diff line number Diff line change
Expand Up @@ -858,9 +858,12 @@ private static function innerRound($value, $scale = 0)
$diffDigit = bcsub($value, $rounded, $scale+1);
$diffDigit = (int)$diffDigit[strlen($diffDigit)-1];

if ($diffDigit >= 5) {
if ($diffDigit >= 5 && $value[0] !== '-') {
$rounded = bcadd($rounded, bcpow('10', -$scale, $scale), $scale);
}
if ($diffDigit >= 5 && $value[0] === '-') {
$rounded = bcsub($rounded, bcpow('10', -$scale, $scale), $scale);
}

return $rounded;
}
Expand Down
8 changes: 8 additions & 0 deletions tests/Decimal/DecimalRoundTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ public function testRoundWithDecimals()
$this->assertTrue(Decimal::fromString('3.44')->round(1)->equals(Decimal::fromString('3.4')));
}

public function testNegativeRoundWithDecimals()
{
$this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(3)->equals(Decimal::fromString('-5.591')));
$this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(4)->equals(Decimal::fromString('-5.5906')));
$this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(5)->equals(Decimal::fromString('-5.59060')));
$this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(6)->equals(Decimal::fromString('-5.590600')));
}

public function testNoUsefulRound()
{
$this->assertTrue(Decimal::fromString('3.45')->round(2)->equals(Decimal::fromString('3.45')));
Expand Down

0 comments on commit a9a28af

Please sign in to comment.