Skip to content

Commit 2b26490

Browse files
committed
Fix up precision loss for defined smaller scale.
1 parent fce3d88 commit 2b26490

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/Decimal.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -871,8 +871,12 @@ protected function fromScientific(string $value, ?int $scale): void
871871
protected function setScale(?int $scale, bool $strict): void
872872
{
873873
$calculatedScale = strlen($this->fractionalPart);
874-
if ($strict && $scale && $calculatedScale > $scale) {
875-
throw new InvalidArgumentException('Loss of precision detected. Detected scale `' . $calculatedScale . '` > `' . $scale . '` as defined.');
874+
if ($scale && $calculatedScale > $scale) {
875+
if ($strict) {
876+
throw new InvalidArgumentException('Loss of precision detected. Detected scale `' . $calculatedScale . '` > `' . $scale . '` as defined.');
877+
}
878+
879+
$this->fractionalPart = substr($this->fractionalPart, 0, $scale);
876880
}
877881

878882
$this->scale = $scale ?? $calculatedScale;

tests/DecimalTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1031,6 +1031,18 @@ public function testDebugInfo(): void
10311031
$this->assertEquals($expected, $result);
10321032
}
10331033

1034+
/**
1035+
* @return void
1036+
*/
1037+
public function testPrecisionLoss(): void
1038+
{
1039+
$a = Decimal::create('0.123456789', 10);
1040+
$this->assertSame('0.123456789', (string)$a);
1041+
1042+
$b = Decimal::create((string)$a, 8);
1043+
$this->assertSame('0.12345678', (string)$b);
1044+
}
1045+
10341046
/**
10351047
* @return void
10361048
*/

0 commit comments

Comments
 (0)