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

Commit a9a28af

Browse files
committed
Fix of the rounding error for negative numbers.
1 parent d47cf15 commit a9a28af

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

src/Decimal.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -858,9 +858,12 @@ private static function innerRound($value, $scale = 0)
858858
$diffDigit = bcsub($value, $rounded, $scale+1);
859859
$diffDigit = (int)$diffDigit[strlen($diffDigit)-1];
860860

861-
if ($diffDigit >= 5) {
861+
if ($diffDigit >= 5 && $value[0] !== '-') {
862862
$rounded = bcadd($rounded, bcpow('10', -$scale, $scale), $scale);
863863
}
864+
if ($diffDigit >= 5 && $value[0] === '-') {
865+
$rounded = bcsub($rounded, bcpow('10', -$scale, $scale), $scale);
866+
}
864867

865868
return $rounded;
866869
}

tests/Decimal/DecimalRoundTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,14 @@ public function testRoundWithDecimals()
2323
$this->assertTrue(Decimal::fromString('3.44')->round(1)->equals(Decimal::fromString('3.4')));
2424
}
2525

26+
public function testNegativeRoundWithDecimals()
27+
{
28+
$this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(3)->equals(Decimal::fromString('-5.591')));
29+
$this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(4)->equals(Decimal::fromString('-5.5906')));
30+
$this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(5)->equals(Decimal::fromString('-5.59060')));
31+
$this->assertTrue(Decimal::fromString('-5.59059956723478932512')->round(6)->equals(Decimal::fromString('-5.590600')));
32+
}
33+
2634
public function testNoUsefulRound()
2735
{
2836
$this->assertTrue(Decimal::fromString('3.45')->round(2)->equals(Decimal::fromString('3.45')));

0 commit comments

Comments
 (0)