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

Commit

Permalink
Merge pull request #31 from punkka/rounding-fix
Browse files Browse the repository at this point in the history
Fix of the rounding error for negative numbers, from @punkka .
  • Loading branch information
castarco committed Apr 3, 2015
2 parents d47cf15 + bacb07c commit c76a4f1
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
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
2 changes: 1 addition & 1 deletion tests/Decimal/DecimalCosTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public function cosProvider() {
return array(
array('1', '0.54030230586814', 14),
array('123.123', '-0.82483472946164834', 17),
array('15000000000', '-0.72218064388924347681', 20)
array('15000000000', '-0.72218064388924347683', 20)
);
}

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 c76a4f1

Please sign in to comment.