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

brick / math / 21806924673

08 Feb 2026 10:42PM UTC coverage: 98.914% (-0.3%) from 99.188%
21806924673

push

github

BenMorel
Optimize BigRational::compareTo()

6 of 6 new or added lines in 1 file covered. (100.0%)

104 existing lines in 5 files now uncovered.

1366 of 1381 relevant lines covered (98.91%)

2312.69 hits per line

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

99.57
/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\CalculatorRegistry;
13
use Brick\Math\Internal\DecimalHelper;
14
use LogicException;
15
use Override;
16

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

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

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

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

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

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

92
        return new BigDecimal($value, $scale);
279✔
93
    }
94

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

105
        if ($zero === null) {
24✔
106
            $zero = new BigDecimal('0');
3✔
107
        }
108

109
        return $zero;
24✔
110
    }
111

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

122
        if ($one === null) {
30✔
123
            $one = new BigDecimal('1');
3✔
124
        }
125

126
        return $one;
30✔
127
    }
128

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

139
        if ($ten === null) {
3✔
140
            $ten = new BigDecimal('10');
3✔
141
        }
142

143
        return $ten;
3✔
144
    }
145

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

161
        if ($that->isZero() && $that->scale <= $this->scale) {
264✔
162
            return $this;
24✔
163
        }
164

165
        if ($this->isZero() && $this->scale <= $that->scale) {
240✔
166
            return $that;
48✔
167
        }
168

169
        [$a, $b] = $this->scaleValues($this, $that);
216✔
170

171
        $value = CalculatorRegistry::get()->add($a, $b);
216✔
172
        $scale = max($this->scale, $that->scale);
216✔
173

174
        return new BigDecimal($value, $scale);
216✔
175
    }
176

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

192
        if ($that->isZero() && $that->scale <= $this->scale) {
168✔
193
            return $this;
15✔
194
        }
195

196
        if ($this->isZero() && $this->scale <= $that->scale) {
153✔
197
            return $that->negated();
9✔
198
        }
199

200
        [$a, $b] = $this->scaleValues($this, $that);
144✔
201

202
        $value = CalculatorRegistry::get()->sub($a, $b);
144✔
203
        $scale = max($this->scale, $that->scale);
144✔
204

205
        return new BigDecimal($value, $scale);
144✔
206
    }
207

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

223
        if ($that->isOneScaleZero()) {
246✔
224
            return $this;
15✔
225
        }
226

227
        if ($this->isOneScaleZero()) {
231✔
228
            return $that;
9✔
229
        }
230

231
        if ($that->isZero() || $this->isZero()) {
222✔
232
            return new BigDecimal('0', $this->scale + $that->scale);
54✔
233
        }
234

235
        $value = CalculatorRegistry::get()->mul($this->value, $that->value);
168✔
236
        $scale = $this->scale + $that->scale;
168✔
237

238
        return new BigDecimal($value, $scale);
168✔
239
    }
240

241
    /**
242
     * Returns the result of the division of this number by the given one, at the given scale.
243
     *
244
     * @param BigNumber|int|string $that         The divisor. Must be convertible to a BigDecimal.
245
     * @param int                  $scale        The desired scale. Must be non-negative.
246
     * @param RoundingMode         $roundingMode An optional rounding mode, defaults to Unnecessary.
247
     *
248
     * @throws InvalidArgumentException   If the scale is negative.
249
     * @throws MathException              If the divisor is not valid, or is not convertible to a BigDecimal.
250
     * @throws DivisionByZeroException    If the divisor is zero.
251
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used and the result cannot be represented exactly at the given scale.
252
     *
253
     * @pure
254
     */
255
    public function dividedBy(BigNumber|int|string $that, int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
256
    {
257
        if ($scale < 0) {
1,905✔
258
            throw InvalidArgumentException::negativeScale();
3✔
259
        }
260

261
        $that = BigDecimal::of($that);
1,902✔
262

263
        if ($that->isZero()) {
1,902✔
264
            throw DivisionByZeroException::divisionByZero();
12✔
265
        }
266

267
        if ($that->isOneScaleZero() && $scale === $this->scale) {
1,890✔
268
            return $this;
114✔
269
        }
270

271
        $p = $this->valueWithMinScale($that->scale + $scale);
1,776✔
272
        $q = $that->valueWithMinScale($this->scale - $scale);
1,776✔
273

274
        $calculator = CalculatorRegistry::get();
1,776✔
275
        $result = $calculator->divRound($p, $q, $roundingMode);
1,776✔
276

277
        if ($result === null) {
1,776✔
278
            [$a, $b] = $this->scaleValues($this->abs(), $that->abs());
129✔
279

280
            $denominator = $calculator->divQ($b, $calculator->gcd($a, $b));
129✔
281
            $requiredScale = DecimalHelper::computeScaleFromReducedFractionDenominator($denominator);
129✔
282

283
            if ($requiredScale === null) {
129✔
284
                throw RoundingNecessaryException::decimalDivisionNotExact();
9✔
285
            }
286

287
            throw RoundingNecessaryException::decimalDivisionScaleTooSmall();
120✔
288
        }
289

290
        return new BigDecimal($result, $scale);
1,647✔
291
    }
292

293
    /**
294
     * Returns the exact result of the division of this number by the given one.
295
     *
296
     * The scale of the result is automatically calculated to fit all the fraction digits.
297
     *
298
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigDecimal.
299
     *
300
     * @throws MathException              If the divisor is not valid, or is not convertible to a BigDecimal.
301
     * @throws DivisionByZeroException    If the divisor is zero.
302
     * @throws RoundingNecessaryException If the result yields an infinite number of digits.
303
     *
304
     * @pure
305
     */
306
    public function dividedByExact(BigNumber|int|string $that): BigDecimal
307
    {
308
        $that = BigDecimal::of($that);
93✔
309

310
        if ($that->isZero()) {
93✔
311
            throw DivisionByZeroException::divisionByZero();
9✔
312
        }
313

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

316
        $calculator = CalculatorRegistry::get();
84✔
317

318
        $denominator = $calculator->divQ($b, $calculator->gcd($a, $b));
84✔
319
        $scale = DecimalHelper::computeScaleFromReducedFractionDenominator($denominator);
84✔
320

321
        if ($scale === null) {
84✔
322
            throw RoundingNecessaryException::decimalDivisionNotExact();
12✔
323
        }
324

325
        return $this->dividedBy($that, $scale)->strippedOfTrailingZeros();
72✔
326
    }
327

328
    /**
329
     * Returns this number exponentiated to the given value.
330
     *
331
     * The result has a scale of `$this->scale * $exponent`.
332
     *
333
     * @throws InvalidArgumentException If the exponent is negative.
334
     *
335
     * @pure
336
     */
337
    public function power(int $exponent): BigDecimal
338
    {
339
        if ($exponent === 0) {
117✔
340
            return BigDecimal::one();
27✔
341
        }
342

343
        if ($exponent === 1) {
90✔
344
            return $this;
21✔
345
        }
346

347
        if ($exponent < 0) {
69✔
348
            throw InvalidArgumentException::negativeExponent();
3✔
349
        }
350

351
        return new BigDecimal(CalculatorRegistry::get()->pow($this->value, $exponent), $this->scale * $exponent);
66✔
352
    }
353

354
    /**
355
     * Returns the quotient of the division of this number by the given one.
356
     *
357
     * The quotient has a scale of `0`.
358
     *
359
     * Examples:
360
     *
361
     * - `7.5` quotient `3` returns `2`
362
     * - `7.5` quotient `-3` returns `-2`
363
     * - `-7.5` quotient `3` returns `-2`
364
     * - `-7.5` quotient `-3` returns `2`
365
     *
366
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigDecimal.
367
     *
368
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigDecimal.
369
     * @throws DivisionByZeroException If the divisor is zero.
370
     *
371
     * @pure
372
     */
373
    public function quotient(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
        $quotient = CalculatorRegistry::get()->divQ($p, $q);
156✔
385

386
        return new BigDecimal($quotient, 0);
156✔
387
    }
388

389
    /**
390
     * Returns the remainder of the division of this number by the given one.
391
     *
392
     * The remainder has a scale of `max($this->scale, $that->scale)`.
393
     * The remainder, when non-zero, has the same sign as the dividend.
394
     *
395
     * Examples:
396
     *
397
     * - `7.5` remainder `3` returns `1.5`
398
     * - `7.5` remainder `-3` returns `1.5`
399
     * - `-7.5` remainder `3` returns `-1.5`
400
     * - `-7.5` remainder `-3` returns `-1.5`
401
     *
402
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigDecimal.
403
     *
404
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigDecimal.
405
     * @throws DivisionByZeroException If the divisor is zero.
406
     *
407
     * @pure
408
     */
409
    public function remainder(BigNumber|int|string $that): BigDecimal
410
    {
411
        $that = BigDecimal::of($that);
159✔
412

413
        if ($that->isZero()) {
159✔
414
            throw DivisionByZeroException::divisionByZero();
3✔
415
        }
416

417
        $p = $this->valueWithMinScale($that->scale);
156✔
418
        $q = $that->valueWithMinScale($this->scale);
156✔
419

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

422
        $scale = max($this->scale, $that->scale);
156✔
423

424
        return new BigDecimal($remainder, $scale);
156✔
425
    }
426

427
    /**
428
     * Returns the quotient and remainder of the division of this number by the given one.
429
     *
430
     * The quotient has a scale of `0`, and the remainder has a scale of `max($this->scale, $that->scale)`.
431
     *
432
     * Examples:
433
     *
434
     * - `7.5` quotientAndRemainder `3` returns [`2`, `1.5`]
435
     * - `7.5` quotientAndRemainder `-3` returns [`-2`, `1.5`]
436
     * - `-7.5` quotientAndRemainder `3` returns [`-2`, `-1.5`]
437
     * - `-7.5` quotientAndRemainder `-3` returns [`2`, `-1.5`]
438
     *
439
     * @param BigNumber|int|string $that The divisor. Must be convertible to a BigDecimal.
440
     *
441
     * @return array{BigDecimal, BigDecimal} An array containing the quotient and the remainder.
442
     *
443
     * @throws MathException           If the divisor is not valid, or is not convertible to a BigDecimal.
444
     * @throws DivisionByZeroException If the divisor is zero.
445
     *
446
     * @pure
447
     */
448
    public function quotientAndRemainder(BigNumber|int|string $that): array
449
    {
450
        $that = BigDecimal::of($that);
159✔
451

452
        if ($that->isZero()) {
159✔
453
            throw DivisionByZeroException::divisionByZero();
3✔
454
        }
455

456
        $p = $this->valueWithMinScale($that->scale);
156✔
457
        $q = $that->valueWithMinScale($this->scale);
156✔
458

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

461
        $scale = max($this->scale, $that->scale);
156✔
462

463
        $quotient = new BigDecimal($quotient, 0);
156✔
464
        $remainder = new BigDecimal($remainder, $scale);
156✔
465

466
        return [$quotient, $remainder];
156✔
467
    }
468

469
    /**
470
     * Returns the square root of this number, rounded to the given scale according to the given rounding mode.
471
     *
472
     * @param int          $scale        The target scale. Must be non-negative.
473
     * @param RoundingMode $roundingMode An optional rounding mode, defaults to Unnecessary.
474
     *
475
     * @throws InvalidArgumentException   If the scale is negative.
476
     * @throws NegativeNumberException    If this number is negative.
477
     * @throws RoundingNecessaryException If RoundingMode::Unnecessary is used, but rounding is necessary.
478
     *
479
     * @pure
480
     */
481
    public function sqrt(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
482
    {
483
        if ($scale < 0) {
6,150✔
484
            throw InvalidArgumentException::negativeScale();
3✔
485
        }
486

487
        if ($this->isZero()) {
6,147✔
488
            return new BigDecimal('0', $scale);
120✔
489
        }
490

491
        if ($this->isNegative()) {
6,027✔
492
            throw NegativeNumberException::squareRootOfNegativeNumber();
3✔
493
        }
494

495
        $value = $this->value;
6,024✔
496
        $inputScale = $this->scale;
6,024✔
497

498
        if ($inputScale % 2 !== 0) {
6,024✔
499
            $value .= '0';
2,346✔
500
            $inputScale++;
2,346✔
501
        }
502

503
        $calculator = CalculatorRegistry::get();
6,024✔
504

505
        // Keep one extra digit for rounding.
506
        $intermediateScale = max($scale, intdiv($inputScale, 2)) + 1;
6,024✔
507
        $value .= str_repeat('0', 2 * $intermediateScale - $inputScale);
6,024✔
508

509
        $sqrt = $calculator->sqrt($value);
6,024✔
510
        $isExact = $calculator->mul($sqrt, $sqrt) === $value;
6,024✔
511

512
        if (! $isExact) {
6,024✔
513
            if ($roundingMode === RoundingMode::Unnecessary) {
3,774✔
514
                throw RoundingNecessaryException::decimalSquareRootNotExact();
375✔
515
            }
516

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

523
            // Irrational sqrt cannot land exactly on a midpoint; treat tie-to-down modes as HalfUp.
524
            elseif (in_array($roundingMode, [RoundingMode::HalfDown, RoundingMode::HalfEven, RoundingMode::HalfFloor], true)) {
2,625✔
525
                $roundingMode = RoundingMode::HalfUp;
1,125✔
526
            }
527
        }
528

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

531
        if ($scaled === null) {
5,649✔
532
            throw RoundingNecessaryException::decimalSquareRootScaleTooSmall();
42✔
533
        }
534

535
        return new BigDecimal($scaled, $scale);
5,607✔
536
    }
537

538
    /**
539
     * Returns a copy of this BigDecimal with the decimal point moved to the left by the given number of places.
540
     *
541
     * @pure
542
     */
543
    public function withPointMovedLeft(int $places): BigDecimal
544
    {
545
        if ($places === 0) {
231✔
546
            return $this;
33✔
547
        }
548

549
        if ($places < 0) {
198✔
550
            return $this->withPointMovedRight(-$places);
66✔
551
        }
552

553
        return new BigDecimal($this->value, $this->scale + $places);
132✔
554
    }
555

556
    /**
557
     * Returns a copy of this BigDecimal with the decimal point moved to the right by the given number of places.
558
     *
559
     * @pure
560
     */
561
    public function withPointMovedRight(int $places): BigDecimal
562
    {
563
        if ($places === 0) {
231✔
564
            return $this;
33✔
565
        }
566

567
        if ($places < 0) {
198✔
568
            return $this->withPointMovedLeft(-$places);
66✔
569
        }
570

571
        $value = $this->value;
132✔
572
        $scale = $this->scale - $places;
132✔
573

574
        if ($scale < 0) {
132✔
575
            if ($value !== '0') {
78✔
576
                $value .= str_repeat('0', -$scale);
60✔
577
            }
578
            $scale = 0;
78✔
579
        }
580

581
        return new BigDecimal($value, $scale);
132✔
582
    }
583

584
    /**
585
     * Returns a copy of this BigDecimal with any trailing zeros removed from the fractional part.
586
     *
587
     * @pure
588
     */
589
    public function strippedOfTrailingZeros(): BigDecimal
590
    {
591
        if ($this->scale === 0) {
453✔
592
            return $this;
114✔
593
        }
594

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

597
        if ($trimmedValue === '') {
339✔
598
            return BigDecimal::zero();
9✔
599
        }
600

601
        $trimmableZeros = strlen($this->value) - strlen($trimmedValue);
330✔
602

603
        if ($trimmableZeros === 0) {
330✔
604
            return $this;
282✔
605
        }
606

607
        if ($trimmableZeros > $this->scale) {
48✔
608
            $trimmableZeros = $this->scale;
12✔
609
        }
610

611
        $value = substr($this->value, 0, -$trimmableZeros);
48✔
612
        $scale = $this->scale - $trimmableZeros;
48✔
613

614
        return new BigDecimal($value, $scale);
48✔
615
    }
616

617
    #[Override]
618
    public function negated(): static
619
    {
620
        return new BigDecimal(CalculatorRegistry::get()->neg($this->value), $this->scale);
1,410✔
621
    }
622

623
    #[Override]
624
    public function compareTo(BigNumber|int|string $that): int
625
    {
626
        $that = BigNumber::of($that);
858✔
627

628
        if ($that instanceof BigInteger) {
858✔
629
            $that = $that->toBigDecimal();
504✔
630
        }
631

632
        if ($that instanceof BigDecimal) {
858✔
633
            [$a, $b] = $this->scaleValues($this, $that);
789✔
634

635
            return CalculatorRegistry::get()->cmp($a, $b);
789✔
636
        }
637

638
        return -$that->compareTo($this);
69✔
639
    }
640

641
    #[Override]
642
    public function getSign(): int
643
    {
644
        return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
9,276✔
645
    }
646

647
    /**
648
     * @pure
649
     */
650
    public function getUnscaledValue(): BigInteger
651
    {
652
        return self::newBigInteger($this->value);
2,892✔
653
    }
654

655
    /**
656
     * @pure
657
     */
658
    public function getScale(): int
659
    {
660
        return $this->scale;
2,892✔
661
    }
662

663
    /**
664
     * Returns the number of significant digits in the number.
665
     *
666
     * This is the number of digits in the unscaled value of the number.
667
     * The sign has no impact on the result.
668
     *
669
     * Examples:
670
     *   0 => 1
671
     *   0.0 => 1
672
     *   123 => 3
673
     *   123.456 => 6
674
     *   0.00123 => 3
675
     *   0.0012300 => 5
676
     *
677
     * @pure
678
     */
679
    public function getPrecision(): int
680
    {
681
        $length = strlen($this->value);
81✔
682

683
        return ($this->value[0] === '-') ? $length - 1 : $length;
81✔
684
    }
685

686
    /**
687
     * Returns the integral part of this decimal number.
688
     *
689
     * Examples:
690
     *
691
     * - `123.456` returns `123`
692
     * - `-123.456` returns `-123`
693
     * - `0.123` returns `0`
694
     * - `-0.123` returns `0`
695
     *
696
     * The following identity holds: `$d->isEqualTo($d->getFractionalPart()->plus($d->getIntegralPart()))`.
697
     *
698
     * @pure
699
     */
700
    public function getIntegralPart(): BigInteger
701
    {
702
        if ($this->scale === 0) {
42✔
703
            return self::newBigInteger($this->value);
9✔
704
        }
705

706
        $value = DecimalHelper::padUnscaledValue($this->value, $this->scale);
33✔
707
        $integerPart = substr($value, 0, -$this->scale);
33✔
708

709
        if ($integerPart === '-0') {
33✔
710
            $integerPart = '0';
3✔
711
        }
712

713
        return self::newBigInteger($integerPart);
33✔
714
    }
715

716
    /**
717
     * Returns the fractional part of this decimal number.
718
     *
719
     * Examples:
720
     *
721
     * - `123.456` returns `0.456`
722
     * - `-123.456` returns `-0.456`
723
     * - `123` returns `0`
724
     * - `-123` returns `0`
725
     *
726
     * The following identity holds: `$d->isEqualTo($d->getFractionalPart()->plus($d->getIntegralPart()))`.
727
     *
728
     * @pure
729
     */
730
    public function getFractionalPart(): BigDecimal
731
    {
732
        if ($this->scale === 0) {
42✔
733
            return BigDecimal::zero();
9✔
734
        }
735

736
        return $this->minus($this->getIntegralPart());
33✔
737
    }
738

739
    #[Override]
740
    public function toBigInteger(): BigInteger
741
    {
742
        if ($this->scale === 0) {
252✔
743
            return self::newBigInteger($this->value);
135✔
744
        }
745

746
        $rational = $this->toBigRational();
138✔
747
        $integralPart = $rational->getIntegralPart();
138✔
748

749
        if ($rational->isEqualTo($integralPart)) {
138✔
750
            return $integralPart;
87✔
751
        }
752

753
        throw RoundingNecessaryException::decimalNotConvertibleToInteger();
51✔
754
    }
755

756
    #[Override]
757
    public function toBigDecimal(): BigDecimal
758
    {
759
        return $this;
8,775✔
760
    }
761

762
    #[Override]
763
    public function toBigRational(): BigRational
764
    {
765
        $numerator = self::newBigInteger($this->value);
495✔
766
        $denominator = self::newBigInteger('1' . str_repeat('0', $this->scale));
495✔
767

768
        return self::newBigRational($numerator, $denominator, false, true);
495✔
769
    }
770

771
    #[Override]
772
    public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::Unnecessary): BigDecimal
773
    {
774
        if ($scale < 0) {
75✔
UNCOV
775
            throw InvalidArgumentException::negativeScale();
×
776
        }
777

778
        if ($scale === $this->scale) {
75✔
779
            return $this;
15✔
780
        }
781

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

784
        if ($value === null) {
60✔
785
            throw RoundingNecessaryException::decimalScaleTooSmall();
9✔
786
        }
787

788
        return new BigDecimal($value, $scale);
51✔
789
    }
790

791
    #[Override]
792
    public function toInt(): int
793
    {
794
        return $this->toBigInteger()->toInt();
33✔
795
    }
796

797
    #[Override]
798
    public function toFloat(): float
799
    {
800
        return (float) $this->toString();
117✔
801
    }
802

803
    /**
804
     * @return numeric-string
805
     */
806
    #[Override]
807
    public function toString(): string
808
    {
809
        if ($this->scale === 0) {
7,203✔
810
            /** @var numeric-string */
811
            return $this->value;
1,593✔
812
        }
813

814
        $value = DecimalHelper::padUnscaledValue($this->value, $this->scale);
5,655✔
815

816
        /** @phpstan-ignore return.type */
817
        return substr($value, 0, -$this->scale) . '.' . substr($value, -$this->scale);
5,655✔
818
    }
819

820
    /**
821
     * This method is required for serializing the object and SHOULD NOT be accessed directly.
822
     *
823
     * @internal
824
     *
825
     * @return array{value: string, scale: int}
826
     */
827
    public function __serialize(): array
828
    {
829
        return ['value' => $this->value, 'scale' => $this->scale];
3✔
830
    }
831

832
    /**
833
     * This method is only here to allow unserializing the object and cannot be accessed directly.
834
     *
835
     * @internal
836
     *
837
     * @param array{value: string, scale: int} $data
838
     *
839
     * @throws LogicException
840
     */
841
    public function __unserialize(array $data): void
842
    {
843
        /** @phpstan-ignore isset.initializedProperty */
844
        if (isset($this->value)) {
6✔
845
            throw new LogicException('__unserialize() is an internal function, it must not be called directly.');
3✔
846
        }
847

848
        /** @phpstan-ignore deadCode.unreachable */
849
        $this->value = $data['value'];
3✔
850
        $this->scale = $data['scale'];
3✔
851
    }
852

853
    #[Override]
854
    protected static function from(BigNumber $number): static
855
    {
856
        return $number->toBigDecimal();
11,664✔
857
    }
858

859
    /**
860
     * Puts the internal values of the given decimal numbers on the same scale.
861
     *
862
     * @return array{string, string} The scaled integer values of $x and $y.
863
     *
864
     * @pure
865
     */
866
    private function scaleValues(BigDecimal $x, BigDecimal $y): array
867
    {
868
        $a = $x->value;
1,314✔
869
        $b = $y->value;
1,314✔
870

871
        if ($b !== '0' && $x->scale > $y->scale) {
1,314✔
872
            $b .= str_repeat('0', $x->scale - $y->scale);
501✔
873
        } elseif ($a !== '0' && $x->scale < $y->scale) {
870✔
874
            $a .= str_repeat('0', $y->scale - $x->scale);
198✔
875
        }
876

877
        return [$a, $b];
1,314✔
878
    }
879

880
    /**
881
     * @pure
882
     */
883
    private function valueWithMinScale(int $scale): string
884
    {
885
        $value = $this->value;
1,932✔
886

887
        if ($this->value !== '0' && $scale > $this->scale) {
1,932✔
888
            $value .= str_repeat('0', $scale - $this->scale);
1,770✔
889
        }
890

891
        return $value;
1,932✔
892
    }
893

894
    /**
895
     * @pure
896
     */
897
    private function isOneScaleZero(): bool
898
    {
899
        return $this->scale === 0 && $this->value === '1';
2,136✔
900
    }
901
}
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