• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

brick / math / 21754808644

06 Feb 2026 02:51PM UTC coverage: 99.172% (-0.2%) from 99.369%
21754808644

push

github

BenMorel
Specific exception messages in Big(Integer|Decimal)::dividedBy()

7 of 7 new or added lines in 4 files covered. (100.0%)

1 existing line in 1 file now uncovered.

1317 of 1328 relevant lines covered (99.17%)

2332.69 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

99.53
/src/BigDecimal.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Brick\Math;
6

7
use Brick\Math\Exception\DivisionByZeroException;
8
use Brick\Math\Exception\InvalidArgumentException;
9
use Brick\Math\Exception\MathException;
10
use Brick\Math\Exception\NegativeNumberException;
11
use Brick\Math\Exception\RoundingNecessaryException;
12
use Brick\Math\Internal\Calculator;
13
use Brick\Math\Internal\CalculatorRegistry;
14
use Brick\Math\Internal\DecimalHelper;
15
use LogicException;
16
use Override;
17

18
use function in_array;
19
use function intdiv;
20
use function max;
21
use function rtrim;
22
use function str_repeat;
23
use function strlen;
24
use function substr;
25

26
/**
27
 * An arbitrarily large decimal number.
28
 *
29
 * This class is immutable.
30
 *
31
 * The scale of the number is the number of digits after the decimal point. It is always positive or zero.
32
 */
33
final readonly class BigDecimal extends BigNumber
34
{
35
    /**
36
     * The unscaled value of this decimal number.
37
     *
38
     * This is a string of digits with an optional leading minus sign.
39
     * No leading zero must be present.
40
     * No leading minus sign must be present if the value is 0.
41
     */
42
    private string $value;
43

44
    /**
45
     * The scale (number of digits after the decimal point) of this decimal number.
46
     *
47
     * This must be zero or more.
48
     */
49
    private int $scale;
50

51
    /**
52
     * Protected constructor. Use a factory method to obtain an instance.
53
     *
54
     * @param string $value The unscaled value, validated.
55
     * @param int    $scale The scale, validated.
56
     *
57
     * @pure
58
     */
59
    protected function __construct(string $value, int $scale = 0)
60
    {
61
        $this->value = $value;
12,342✔
62
        $this->scale = $scale;
12,342✔
63
    }
64

65
    /**
66
     * Creates a BigDecimal from an unscaled value and a scale.
67
     *
68
     * Example: `(12345, 3)` will result in the BigDecimal `12.345`.
69
     *
70
     * @param BigNumber|int|string $value The unscaled value. Must be convertible to a BigInteger.
71
     * @param int                  $scale The scale of the number. If negative, the scale will be set to zero
72
     *                                    and the unscaled value will be adjusted accordingly.
73
     *
74
     * @throws MathException If the value is not valid, or is not convertible to a BigInteger.
75
     *
76
     * @pure
77
     */
78
    public static function ofUnscaledValue(BigNumber|int|string $value, int $scale = 0): BigDecimal
79
    {
80
        $value = BigInteger::of($value)->toString();
279✔
81

82
        if ($scale < 0) {
279✔
83
            if ($value !== '0') {
66✔
84
                $value .= str_repeat('0', -$scale);
54✔
85
            }
86
            $scale = 0;
66✔
87
        }
88

89
        return new BigDecimal($value, $scale);
279✔
90
    }
91

92
    /**
93
     * Returns a BigDecimal representing zero, with a scale of zero.
94
     *
95
     * @pure
96
     */
97
    public static function zero(): BigDecimal
98
    {
99
        /** @var BigDecimal|null $zero */
100
        static $zero;
15✔
101

102
        if ($zero === null) {
15✔
103
            $zero = new BigDecimal('0');
3✔
104
        }
105

106
        return $zero;
15✔
107
    }
108

109
    /**
110
     * Returns a BigDecimal representing one, with a scale of zero.
111
     *
112
     * @pure
113
     */
114
    public static function one(): BigDecimal
115
    {
116
        /** @var BigDecimal|null $one */
117
        static $one;
30✔
118

119
        if ($one === null) {
30✔
120
            $one = new BigDecimal('1');
3✔
121
        }
122

123
        return $one;
30✔
124
    }
125

126
    /**
127
     * Returns a BigDecimal representing ten, with a scale of zero.
128
     *
129
     * @pure
130
     */
131
    public static function ten(): BigDecimal
132
    {
133
        /** @var BigDecimal|null $ten */
134
        static $ten;
3✔
135

136
        if ($ten === null) {
3✔
137
            $ten = new BigDecimal('10');
3✔
138
        }
139

140
        return $ten;
3✔
141
    }
142

143
    /**
144
     * Returns the sum of this number and the given one.
145
     *
146
     * The result has a scale of `max($this->scale, $that->scale)`.
147
     *
148
     * @param BigNumber|int|string $that The number to add. Must be convertible to a BigDecimal.
149
     *
150
     * @throws MathException If the number is not valid, or is not convertible to a BigDecimal.
151
     *
152
     * @pure
153
     */
154
    public function plus(BigNumber|int|string $that): BigDecimal
155
    {
156
        $that = BigDecimal::of($that);
222✔
157

158
        if ($that->value === '0' && $that->scale <= $this->scale) {
222✔
159
            return $this;
12✔
160
        }
161

162
        if ($this->value === '0' && $this->scale <= $that->scale) {
210✔
163
            return $that;
42✔
164
        }
165

166
        [$a, $b] = $this->scaleValues($this, $that);
192✔
167

168
        $value = CalculatorRegistry::get()->add($a, $b);
192✔
169
        $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
192✔
170

171
        return new BigDecimal($value, $scale);
192✔
172
    }
173

174
    /**
175
     * Returns the difference of this number and the given one.
176
     *
177
     * The result has a scale of `max($this->scale, $that->scale)`.
178
     *
179
     * @param BigNumber|int|string $that The number to subtract. Must be convertible to a BigDecimal.
180
     *
181
     * @throws MathException If the number is not valid, or is not convertible to a BigDecimal.
182
     *
183
     * @pure
184
     */
185
    public function minus(BigNumber|int|string $that): BigDecimal
186
    {
187
        $that = BigDecimal::of($that);
135✔
188

189
        if ($that->value === '0' && $that->scale <= $this->scale) {
135✔
190
            return $this;
6✔
191
        }
192

193
        [$a, $b] = $this->scaleValues($this, $that);
129✔
194

195
        $value = CalculatorRegistry::get()->sub($a, $b);
129✔
196
        $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
129✔
197

198
        return new BigDecimal($value, $scale);
129✔
199
    }
200

201
    /**
202
     * Returns the product of this number and the given one.
203
     *
204
     * The result has a scale of `$this->scale + $that->scale`.
205
     *
206
     * @param BigNumber|int|string $that The multiplier. Must be convertible to a BigDecimal.
207
     *
208
     * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigDecimal.
209
     *
210
     * @pure
211
     */
212
    public function multipliedBy(BigNumber|int|string $that): BigDecimal
213
    {
214
        $that = BigDecimal::of($that);
246✔
215

216
        if ($that->value === '1' && $that->scale === 0) {
246✔
217
            return $this;
15✔
218
        }
219

220
        if ($this->value === '1' && $this->scale === 0) {
231✔
221
            return $that;
9✔
222
        }
223

224
        $value = CalculatorRegistry::get()->mul($this->value, $that->value);
222✔
225
        $scale = $this->scale + $that->scale;
222✔
226

227
        return new BigDecimal($value, $scale);
222✔
228
    }
229

230
    /**
231
     * Returns the result of the division of this number by the given one, at the given scale.
232
     *
233
     * @param BigNumber|int|string $that         The divisor. Must be convertible to a BigDecimal.
234
     * @param int                  $scale        The desired scale.
235
     * @param RoundingMode         $roundingMode An optional rounding mode, defaults to Unnecessary.
236
     *
237
     * @throws InvalidArgumentException   If the scale is invalid.
238
     * @throws MathException              If the divisor is not a valid number or is not convertible to a BigDecimal.
239
     * @throws DivisionByZeroException    If the divisor is zero.
240
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used and the result cannot be represented exactly at the given scale.
241
     *
242
     * @pure
243
     */
244
    public function dividedBy(BigNumber|int|string $that, int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
245
    {
246
        $that = BigDecimal::of($that);
1,905✔
247

248
        if ($that->isZero()) {
1,905✔
249
            throw DivisionByZeroException::divisionByZero();
12✔
250
        }
251

252
        if ($scale < 0) {
1,893✔
253
            throw InvalidArgumentException::negativeScale();
3✔
254
        }
255

256
        if ($that->value === '1' && $that->scale === 0 && $scale === $this->scale) {
1,890✔
257
            return $this;
114✔
258
        }
259

260
        $p = $this->valueWithMinScale($that->scale + $scale);
1,776✔
261
        $q = $that->valueWithMinScale($this->scale - $scale);
1,776✔
262

263
        $result = CalculatorRegistry::get()->divRound($p, $q, $roundingMode);
1,776✔
264

265
        if ($result === null) {
1,776✔
266
            throw RoundingNecessaryException::divisionRequiresRounding();
129✔
267
        }
268

269
        return new BigDecimal($result, $scale);
1,647✔
270
    }
271

272
    /**
273
     * Returns the exact result of the division of this number by the given one.
274
     *
275
     * The scale of the result is automatically calculated to fit all the fraction digits.
276
     *
277
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigDecimal.
278
     *
279
     * @throws MathException              If the divisor is not a valid number or is not convertible to a BigDecimal.
280
     * @throws DivisionByZeroException    If the divisor is zero.
281
     * @throws RoundingNecessaryException If the result yields an infinite number of digits.
282
     *
283
     * @pure
284
     */
285
    public function dividedByExact(BigNumber|int|string $that): BigDecimal
286
    {
287
        $that = BigDecimal::of($that);
93✔
288

289
        if ($that->value === '0') {
93✔
290
            throw DivisionByZeroException::divisionByZero();
9✔
291
        }
292

293
        [$a, $b] = $this->scaleValues($this->abs(), $that->abs());
84✔
294

295
        $calculator = CalculatorRegistry::get();
84✔
296

297
        $denominator = $calculator->divQ($b, $calculator->gcd($a, $b));
84✔
298
        $scale = DecimalHelper::computeScaleFromReducedFractionDenominator($denominator);
84✔
299

300
        if ($scale === null) {
84✔
301
            throw RoundingNecessaryException::nonTerminatingDecimal();
12✔
302
        }
303

304
        return $this->dividedBy($that, $scale)->strippedOfTrailingZeros();
72✔
305
    }
306

307
    /**
308
     * Returns this number exponentiated to the given value.
309
     *
310
     * The result has a scale of `$this->scale * $exponent`.
311
     *
312
     * @throws InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
313
     *
314
     * @pure
315
     */
316
    public function power(int $exponent): BigDecimal
317
    {
318
        if ($exponent === 0) {
120✔
319
            return BigDecimal::one();
27✔
320
        }
321

322
        if ($exponent === 1) {
93✔
323
            return $this;
21✔
324
        }
325

326
        if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
72✔
327
            throw InvalidArgumentException::exponentOutOfRange($exponent, 0, Calculator::MAX_POWER);
6✔
328
        }
329

330
        return new BigDecimal(CalculatorRegistry::get()->pow($this->value, $exponent), $this->scale * $exponent);
66✔
331
    }
332

333
    /**
334
     * Returns the quotient of the division of this number by the given one.
335
     *
336
     * The quotient has a scale of `0`.
337
     *
338
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigDecimal.
339
     *
340
     * @throws MathException           If the divisor is not a valid decimal number.
341
     * @throws DivisionByZeroException If the divisor is zero.
342
     *
343
     * @pure
344
     */
345
    public function quotient(BigNumber|int|string $that): BigDecimal
346
    {
347
        $that = BigDecimal::of($that);
159✔
348

349
        if ($that->isZero()) {
159✔
350
            throw DivisionByZeroException::divisionByZero();
3✔
351
        }
352

353
        $p = $this->valueWithMinScale($that->scale);
156✔
354
        $q = $that->valueWithMinScale($this->scale);
156✔
355

356
        $quotient = CalculatorRegistry::get()->divQ($p, $q);
156✔
357

358
        return new BigDecimal($quotient, 0);
156✔
359
    }
360

361
    /**
362
     * Returns the remainder of the division of this number by the given one.
363
     *
364
     * The remainder has a scale of `max($this->scale, $that->scale)`.
365
     *
366
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigDecimal.
367
     *
368
     * @throws MathException           If the divisor is not a valid decimal number.
369
     * @throws DivisionByZeroException If the divisor is zero.
370
     *
371
     * @pure
372
     */
373
    public function remainder(BigNumber|int|string $that): BigDecimal
374
    {
375
        $that = BigDecimal::of($that);
159✔
376

377
        if ($that->isZero()) {
159✔
378
            throw DivisionByZeroException::divisionByZero();
3✔
379
        }
380

381
        $p = $this->valueWithMinScale($that->scale);
156✔
382
        $q = $that->valueWithMinScale($this->scale);
156✔
383

384
        $remainder = CalculatorRegistry::get()->divR($p, $q);
156✔
385

386
        $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
156✔
387

388
        return new BigDecimal($remainder, $scale);
156✔
389
    }
390

391
    /**
392
     * Returns the quotient and remainder of the division of this number by the given one.
393
     *
394
     * The quotient has a scale of `0`, and the remainder has a scale of `max($this->scale, $that->scale)`.
395
     *
396
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigDecimal.
397
     *
398
     * @return array{BigDecimal, BigDecimal} An array containing the quotient and the remainder.
399
     *
400
     * @throws MathException           If the divisor is not a valid decimal number.
401
     * @throws DivisionByZeroException If the divisor is zero.
402
     *
403
     * @pure
404
     */
405
    public function quotientAndRemainder(BigNumber|int|string $that): array
406
    {
407
        $that = BigDecimal::of($that);
159✔
408

409
        if ($that->isZero()) {
159✔
410
            throw DivisionByZeroException::divisionByZero();
3✔
411
        }
412

413
        $p = $this->valueWithMinScale($that->scale);
156✔
414
        $q = $that->valueWithMinScale($this->scale);
156✔
415

416
        [$quotient, $remainder] = CalculatorRegistry::get()->divQR($p, $q);
156✔
417

418
        $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
156✔
419

420
        $quotient = new BigDecimal($quotient, 0);
156✔
421
        $remainder = new BigDecimal($remainder, $scale);
156✔
422

423
        return [$quotient, $remainder];
156✔
424
    }
425

426
    /**
427
     * Returns the square root of this number, rounded to the given scale according to the given rounding mode.
428
     *
429
     * @param int          $scale        The target scale.
430
     * @param RoundingMode $roundingMode The rounding mode to use, defaults to Unnecessary.
431
     *
432
     * @throws InvalidArgumentException   If the scale is negative.
433
     * @throws NegativeNumberException    If this number is negative.
434
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, but rounding is necessary.
435
     *
436
     * @pure
437
     */
438
    public function sqrt(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
439
    {
440
        if ($scale < 0) {
6,150✔
441
            throw InvalidArgumentException::negativeScale();
3✔
442
        }
443

444
        if ($this->value === '0') {
6,147✔
445
            return new BigDecimal('0', $scale);
120✔
446
        }
447

448
        if ($this->value[0] === '-') {
6,027✔
449
            throw NegativeNumberException::squareRootOfNegativeNumber();
3✔
450
        }
451

452
        $value = $this->value;
6,024✔
453
        $inputScale = $this->scale;
6,024✔
454

455
        if ($inputScale % 2 !== 0) {
6,024✔
456
            $value .= '0';
2,346✔
457
            $inputScale++;
2,346✔
458
        }
459

460
        $calculator = CalculatorRegistry::get();
6,024✔
461

462
        // Keep one extra digit for rounding.
463
        $intermediateScale = max($scale, intdiv($inputScale, 2)) + 1;
6,024✔
464
        $value .= str_repeat('0', 2 * $intermediateScale - $inputScale);
6,024✔
465

466
        $sqrt = $calculator->sqrt($value);
6,024✔
467
        $isExact = $calculator->mul($sqrt, $sqrt) === $value;
6,024✔
468

469
        if (! $isExact) {
6,024✔
470
            if ($roundingMode === RoundingMode::Unnecessary) {
3,774✔
471
                throw RoundingNecessaryException::decimalSquareRootNotExact();
375✔
472
            }
473

474
            // Non-perfect-square sqrt is irrational, so the true value is strictly above this sqrt floor.
475
            // Add one at the intermediate scale to guarantee Up/Ceiling round up at the target scale.
476
            if (in_array($roundingMode, [RoundingMode::Up, RoundingMode::Ceiling], true)) {
3,399✔
477
                $sqrt = $calculator->add($sqrt, '1');
774✔
478
            }
479

480
            // Irrational sqrt cannot land exactly on a midpoint; treat tie-to-down modes as HalfUp.
481
            elseif (in_array($roundingMode, [RoundingMode::HalfDown, RoundingMode::HalfEven, RoundingMode::HalfFloor], true)) {
2,625✔
482
                $roundingMode = RoundingMode::HalfUp;
1,125✔
483
            }
484
        }
485

486
        $scaled = DecimalHelper::scale($sqrt, $intermediateScale, $scale, $roundingMode);
5,649✔
487

488
        if ($scaled === null) {
5,649✔
489
            throw RoundingNecessaryException::decimalSquareRootScaleTooSmall();
42✔
490
        }
491

492
        return new BigDecimal($scaled, $scale);
5,607✔
493
    }
494

495
    /**
496
     * Returns a copy of this BigDecimal with the decimal point moved $n places to the left.
497
     *
498
     * @pure
499
     */
500
    public function withPointMovedLeft(int $places): BigDecimal
501
    {
502
        if ($places === 0) {
231✔
503
            return $this;
33✔
504
        }
505

506
        if ($places < 0) {
198✔
507
            return $this->withPointMovedRight(-$places);
66✔
508
        }
509

510
        return new BigDecimal($this->value, $this->scale + $places);
132✔
511
    }
512

513
    /**
514
     * Returns a copy of this BigDecimal with the decimal point moved $n places to the right.
515
     *
516
     * @pure
517
     */
518
    public function withPointMovedRight(int $places): BigDecimal
519
    {
520
        if ($places === 0) {
231✔
521
            return $this;
33✔
522
        }
523

524
        if ($places < 0) {
198✔
525
            return $this->withPointMovedLeft(-$places);
66✔
526
        }
527

528
        $value = $this->value;
132✔
529
        $scale = $this->scale - $places;
132✔
530

531
        if ($scale < 0) {
132✔
532
            if ($value !== '0') {
78✔
533
                $value .= str_repeat('0', -$scale);
60✔
534
            }
535
            $scale = 0;
78✔
536
        }
537

538
        return new BigDecimal($value, $scale);
132✔
539
    }
540

541
    /**
542
     * Returns a copy of this BigDecimal with any trailing zeros removed from the fractional part.
543
     *
544
     * @pure
545
     */
546
    public function strippedOfTrailingZeros(): BigDecimal
547
    {
548
        if ($this->scale === 0) {
453✔
549
            return $this;
114✔
550
        }
551

552
        $trimmedValue = rtrim($this->value, '0');
339✔
553

554
        if ($trimmedValue === '') {
339✔
555
            return BigDecimal::zero();
9✔
556
        }
557

558
        $trimmableZeros = strlen($this->value) - strlen($trimmedValue);
330✔
559

560
        if ($trimmableZeros === 0) {
330✔
561
            return $this;
282✔
562
        }
563

564
        if ($trimmableZeros > $this->scale) {
48✔
565
            $trimmableZeros = $this->scale;
12✔
566
        }
567

568
        $value = substr($this->value, 0, -$trimmableZeros);
48✔
569
        $scale = $this->scale - $trimmableZeros;
48✔
570

571
        return new BigDecimal($value, $scale);
48✔
572
    }
573

574
    #[Override]
575
    public function negated(): static
576
    {
577
        return new BigDecimal(CalculatorRegistry::get()->neg($this->value), $this->scale);
1,344✔
578
    }
579

580
    #[Override]
581
    public function compareTo(BigNumber|int|string $that): int
582
    {
583
        $that = BigNumber::of($that);
783✔
584

585
        if ($that instanceof BigInteger) {
783✔
586
            $that = $that->toBigDecimal();
486✔
587
        }
588

589
        if ($that instanceof BigDecimal) {
783✔
590
            [$a, $b] = $this->scaleValues($this, $that);
729✔
591

592
            return CalculatorRegistry::get()->cmp($a, $b);
729✔
593
        }
594

595
        return -$that->compareTo($this);
54✔
596
    }
597

598
    #[Override]
599
    public function getSign(): int
600
    {
601
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
2,508✔
602
    }
603

604
    /**
605
     * @pure
606
     */
607
    public function getUnscaledValue(): BigInteger
608
    {
609
        return self::newBigInteger($this->value);
2,892✔
610
    }
611

612
    /**
613
     * @pure
614
     */
615
    public function getScale(): int
616
    {
617
        return $this->scale;
2,892✔
618
    }
619

620
    /**
621
     * Returns the number of significant digits in the number.
622
     *
623
     * This is the number of digits in the unscaled value of the number.
624
     * The sign has no impact on the result.
625
     *
626
     * Examples:
627
     *   0 => 1
628
     *   0.0 => 1
629
     *   123 => 3
630
     *   123.456 => 6
631
     *   0.00123 => 3
632
     *   0.0012300 => 5
633
     *
634
     * @pure
635
     */
636
    public function getPrecision(): int
637
    {
638
        $length = strlen($this->value);
81✔
639

640
        return ($this->value[0] === '-') ? $length - 1 : $length;
81✔
641
    }
642

643
    /**
644
     * Returns whether this decimal number has a non-zero fractional part.
645
     *
646
     * @pure
647
     */
648
    public function hasNonZeroFractionalPart(): bool
649
    {
650
        if ($this->scale === 0) {
18✔
651
            return false;
6✔
652
        }
653

654
        $value = DecimalHelper::padUnscaledValue($this->value, $this->scale);
12✔
655

656
        return substr($value, -$this->scale) !== str_repeat('0', $this->scale);
12✔
657
    }
658

659
    #[Override]
660
    public function toBigInteger(): BigInteger
661
    {
662
        if ($this->scale === 0) {
252✔
663
            return self::newBigInteger($this->value);
135✔
664
        }
665

666
        $rational = $this->toBigRational();
138✔
667
        $integralPart = $rational->getIntegralPart();
138✔
668

669
        if ($rational->isEqualTo($integralPart)) {
138✔
670
            return $integralPart;
87✔
671
        }
672

673
        throw RoundingNecessaryException::decimalNotConvertibleToInteger();
51✔
674
    }
675

676
    #[Override]
677
    public function toBigDecimal(): BigDecimal
678
    {
679
        return $this;
8,754✔
680
    }
681

682
    #[Override]
683
    public function toBigRational(): BigRational
684
    {
685
        $numerator = self::newBigInteger($this->value);
474✔
686
        $denominator = self::newBigInteger('1' . str_repeat('0', $this->scale));
474✔
687

688
        return self::newBigRational($numerator, $denominator, false, true);
474✔
689
    }
690

691
    #[Override]
692
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
693
    {
694
        if ($scale === $this->scale) {
75✔
695
            return $this;
15✔
696
        }
697

698
        if ($scale < 0) {
60✔
UNCOV
699
            throw InvalidArgumentException::negativeScale();
×
700
        }
701

702
        $value = DecimalHelper::scale($this->value, $this->scale, $scale, $roundingMode);
60✔
703

704
        if ($value === null) {
60✔
705
            throw RoundingNecessaryException::scaleRequiresRounding();
9✔
706
        }
707

708
        return new BigDecimal($value, $scale);
51✔
709
    }
710

711
    #[Override]
712
    public function toInt(): int
713
    {
714
        return $this->toBigInteger()->toInt();
33✔
715
    }
716

717
    #[Override]
718
    public function toFloat(): float
719
    {
720
        return (float) $this->toString();
117✔
721
    }
722

723
    /**
724
     * @return numeric-string
725
     */
726
    #[Override]
727
    public function toString(): string
728
    {
729
        if ($this->scale === 0) {
7,152✔
730
            /** @var numeric-string */
731
            return $this->value;
1,584✔
732
        }
733

734
        $value = DecimalHelper::padUnscaledValue($this->value, $this->scale);
5,613✔
735

736
        /** @phpstan-ignore return.type */
737
        return substr($value, 0, -$this->scale) . '.' . substr($value, -$this->scale);
5,613✔
738
    }
739

740
    /**
741
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
742
     *
743
     * @internal
744
     *
745
     * @return array{value: string, scale: int}
746
     */
747
    public function __serialize(): array
748
    {
749
        return ['value' => $this->value, 'scale' => $this->scale];
3✔
750
    }
751

752
    /**
753
     * This method is only here to allow unserializing the object and cannot be accessed directly.
754
     *
755
     * @internal
756
     *
757
     * @param array{value: string, scale: int} $data
758
     *
759
     * @throws LogicException
760
     */
761
    public function __unserialize(array $data): void
762
    {
763
        /** @phpstan-ignore isset.initializedProperty */
764
        if (isset($this->value)) {
6✔
765
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
766
        }
767

768
        /** @phpstan-ignore deadCode.unreachable */
769
        $this->value = $data['value'];
3✔
770
        $this->scale = $data['scale'];
3✔
771
    }
772

773
    #[Override]
774
    protected static function from(BigNumber $number): static
775
    {
776
        return $number->toBigDecimal();
11,643✔
777
    }
778

779
    /**
780
     * Puts the internal values of the given decimal numbers on the same scale.
781
     *
782
     * @return array{string, string} The scaled integer values of $x and $y.
783
     *
784
     * @pure
785
     */
786
    private function scaleValues(BigDecimal $x, BigDecimal $y): array
787
    {
788
        $a = $x->value;
1,134✔
789
        $b = $y->value;
1,134✔
790

791
        if ($b !== '0' && $x->scale > $y->scale) {
1,134✔
792
            $b .= str_repeat('0', $x->scale - $y->scale);
345✔
793
        } elseif ($a !== '0' && $x->scale < $y->scale) {
822✔
794
            $a .= str_repeat('0', $y->scale - $x->scale);
198✔
795
        }
796

797
        return [$a, $b];
1,134✔
798
    }
799

800
    /**
801
     * @pure
802
     */
803
    private function valueWithMinScale(int $scale): string
804
    {
805
        $value = $this->value;
1,932✔
806

807
        if ($this->value !== '0' && $scale > $this->scale) {
1,932✔
808
            $value .= str_repeat('0', $scale - $this->scale);
1,770✔
809
        }
810

811
        return $value;
1,932✔
812
    }
813
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc