@@ -65,14 +65,15 @@ class Decimal implements JsonSerializable, Stringable
65
65
/**
66
66
* @param object|string|float|int $value
67
67
* @param int|null $scale Decimal places in the result. Omit to enable auto-detection.
68
+ * @param bool $strict If scale should be strictly checked to avoid accidental precision loss.
68
69
*/
69
- public function __construct (object |string |float |int $ value , ?int $ scale = null )
70
+ public function __construct (object |string |float |int $ value , ?int $ scale = null , bool $ strict = false )
70
71
{
71
72
$ value = $ this ->parseValue ($ value );
72
73
$ value = $ this ->normalizeValue ($ value );
73
74
74
75
$ this ->setValue ($ value , $ scale );
75
- $ this ->setScale ($ scale );
76
+ $ this ->setScale ($ scale, $ strict );
76
77
}
77
78
78
79
/**
@@ -146,16 +147,17 @@ protected function normalizeValue(string $value): string
146
147
*
147
148
* @param object|string|float|int $value
148
149
* @param int|null $scale Decimal places in the result. Omit to enable auto-detection.
150
+ * @param bool $strict If scale should be strictly checked to avoid accidental precision loss.
149
151
*
150
152
* @return static
151
153
*/
152
- public static function create (object |string |float |int $ value , ?int $ scale = null ): static
154
+ public static function create (object |string |float |int $ value , ?int $ scale = null , bool $ strict = false ): static
153
155
{
154
156
if ($ scale === null && $ value instanceof static) {
155
157
return clone $ value ;
156
158
}
157
159
158
- return new static ($ value , $ scale );
160
+ return new static ($ value , $ scale, $ strict );
159
161
}
160
162
161
163
/**
@@ -737,7 +739,7 @@ protected function copy(?string $integerPart = null, ?string $decimalPart = null
737
739
}
738
740
if ($ decimalPart !== null ) {
739
741
$ clone ->fractionalPart = $ decimalPart ;
740
- $ clone ->setScale (null );
742
+ $ clone ->setScale (null , false );
741
743
}
742
744
if ($ negative !== null ) {
743
745
$ clone ->negative = $ negative ;
@@ -860,15 +862,16 @@ protected function fromScientific(string $value, ?int $scale): void
860
862
861
863
/**
862
864
* @param int|null $scale
865
+ * @param bool $strict
863
866
*
864
867
* @throws \InvalidArgumentException
865
868
*
866
869
* @return void
867
870
*/
868
- protected function setScale (?int $ scale ): void
871
+ protected function setScale (?int $ scale, bool $ strict ): void
869
872
{
870
873
$ calculatedScale = strlen ($ this ->fractionalPart );
871
- if ($ scale && $ calculatedScale > $ scale ) {
874
+ if ($ strict && $ scale && $ calculatedScale > $ scale ) {
872
875
throw new InvalidArgumentException ('Loss of precision detected. Detected scale ` ' . $ calculatedScale . '` > ` ' . $ scale . '` as defined. ' );
873
876
}
874
877
0 commit comments