BigDecimal.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. <?php
  2. declare(strict_types=1);
  3. namespace Brick\Math;
  4. use Brick\Math\Exception\DivisionByZeroException;
  5. use Brick\Math\Exception\MathException;
  6. use Brick\Math\Exception\NegativeNumberException;
  7. use Brick\Math\Internal\Calculator;
  8. /**
  9. * Immutable, arbitrary-precision signed decimal numbers.
  10. *
  11. * @psalm-immutable
  12. */
  13. final class BigDecimal extends BigNumber
  14. {
  15. /**
  16. * The unscaled value of this decimal number.
  17. *
  18. * This is a string of digits with an optional leading minus sign.
  19. * No leading zero must be present.
  20. * No leading minus sign must be present if the value is 0.
  21. *
  22. * @var string
  23. */
  24. private $value;
  25. /**
  26. * The scale (number of digits after the decimal point) of this decimal number.
  27. *
  28. * This must be zero or more.
  29. *
  30. * @var int
  31. */
  32. private $scale;
  33. /**
  34. * Protected constructor. Use a factory method to obtain an instance.
  35. *
  36. * @param string $value The unscaled value, validated.
  37. * @param int $scale The scale, validated.
  38. */
  39. protected function __construct(string $value, int $scale = 0)
  40. {
  41. $this->value = $value;
  42. $this->scale = $scale;
  43. }
  44. /**
  45. * Creates a BigDecimal of the given value.
  46. *
  47. * @param BigNumber|int|float|string $value
  48. *
  49. * @return BigDecimal
  50. *
  51. * @throws MathException If the value cannot be converted to a BigDecimal.
  52. *
  53. * @psalm-pure
  54. */
  55. public static function of($value) : BigNumber
  56. {
  57. return parent::of($value)->toBigDecimal();
  58. }
  59. /**
  60. * Creates a BigDecimal from an unscaled value and a scale.
  61. *
  62. * Example: `(12345, 3)` will result in the BigDecimal `12.345`.
  63. *
  64. * @param BigNumber|int|float|string $value The unscaled value. Must be convertible to a BigInteger.
  65. * @param int $scale The scale of the number, positive or zero.
  66. *
  67. * @return BigDecimal
  68. *
  69. * @throws \InvalidArgumentException If the scale is negative.
  70. *
  71. * @psalm-pure
  72. */
  73. public static function ofUnscaledValue($value, int $scale = 0) : BigDecimal
  74. {
  75. if ($scale < 0) {
  76. throw new \InvalidArgumentException('The scale cannot be negative.');
  77. }
  78. return new BigDecimal((string) BigInteger::of($value), $scale);
  79. }
  80. /**
  81. * Returns a BigDecimal representing zero, with a scale of zero.
  82. *
  83. * @return BigDecimal
  84. *
  85. * @psalm-pure
  86. */
  87. public static function zero() : BigDecimal
  88. {
  89. /**
  90. * @psalm-suppress ImpureStaticVariable
  91. * @var BigDecimal|null $zero
  92. */
  93. static $zero;
  94. if ($zero === null) {
  95. $zero = new BigDecimal('0');
  96. }
  97. return $zero;
  98. }
  99. /**
  100. * Returns a BigDecimal representing one, with a scale of zero.
  101. *
  102. * @return BigDecimal
  103. *
  104. * @psalm-pure
  105. */
  106. public static function one() : BigDecimal
  107. {
  108. /**
  109. * @psalm-suppress ImpureStaticVariable
  110. * @var BigDecimal|null $one
  111. */
  112. static $one;
  113. if ($one === null) {
  114. $one = new BigDecimal('1');
  115. }
  116. return $one;
  117. }
  118. /**
  119. * Returns a BigDecimal representing ten, with a scale of zero.
  120. *
  121. * @return BigDecimal
  122. *
  123. * @psalm-pure
  124. */
  125. public static function ten() : BigDecimal
  126. {
  127. /**
  128. * @psalm-suppress ImpureStaticVariable
  129. * @var BigDecimal|null $ten
  130. */
  131. static $ten;
  132. if ($ten === null) {
  133. $ten = new BigDecimal('10');
  134. }
  135. return $ten;
  136. }
  137. /**
  138. * Returns the sum of this number and the given one.
  139. *
  140. * The result has a scale of `max($this->scale, $that->scale)`.
  141. *
  142. * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigDecimal.
  143. *
  144. * @return BigDecimal The result.
  145. *
  146. * @throws MathException If the number is not valid, or is not convertible to a BigDecimal.
  147. */
  148. public function plus($that) : BigDecimal
  149. {
  150. $that = BigDecimal::of($that);
  151. if ($that->value === '0' && $that->scale <= $this->scale) {
  152. return $this;
  153. }
  154. if ($this->value === '0' && $this->scale <= $that->scale) {
  155. return $that;
  156. }
  157. [$a, $b] = $this->scaleValues($this, $that);
  158. $value = Calculator::get()->add($a, $b);
  159. $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
  160. return new BigDecimal($value, $scale);
  161. }
  162. /**
  163. * Returns the difference of this number and the given one.
  164. *
  165. * The result has a scale of `max($this->scale, $that->scale)`.
  166. *
  167. * @param BigNumber|int|float|string $that The number to subtract. Must be convertible to a BigDecimal.
  168. *
  169. * @return BigDecimal The result.
  170. *
  171. * @throws MathException If the number is not valid, or is not convertible to a BigDecimal.
  172. */
  173. public function minus($that) : BigDecimal
  174. {
  175. $that = BigDecimal::of($that);
  176. if ($that->value === '0' && $that->scale <= $this->scale) {
  177. return $this;
  178. }
  179. [$a, $b] = $this->scaleValues($this, $that);
  180. $value = Calculator::get()->sub($a, $b);
  181. $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
  182. return new BigDecimal($value, $scale);
  183. }
  184. /**
  185. * Returns the product of this number and the given one.
  186. *
  187. * The result has a scale of `$this->scale + $that->scale`.
  188. *
  189. * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigDecimal.
  190. *
  191. * @return BigDecimal The result.
  192. *
  193. * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigDecimal.
  194. */
  195. public function multipliedBy($that) : BigDecimal
  196. {
  197. $that = BigDecimal::of($that);
  198. if ($that->value === '1' && $that->scale === 0) {
  199. return $this;
  200. }
  201. if ($this->value === '1' && $this->scale === 0) {
  202. return $that;
  203. }
  204. $value = Calculator::get()->mul($this->value, $that->value);
  205. $scale = $this->scale + $that->scale;
  206. return new BigDecimal($value, $scale);
  207. }
  208. /**
  209. * Returns the result of the division of this number by the given one, at the given scale.
  210. *
  211. * @param BigNumber|int|float|string $that The divisor.
  212. * @param int|null $scale The desired scale, or null to use the scale of this number.
  213. * @param int $roundingMode An optional rounding mode.
  214. *
  215. * @return BigDecimal
  216. *
  217. * @throws \InvalidArgumentException If the scale or rounding mode is invalid.
  218. * @throws MathException If the number is invalid, is zero, or rounding was necessary.
  219. */
  220. public function dividedBy($that, ?int $scale = null, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
  221. {
  222. $that = BigDecimal::of($that);
  223. if ($that->isZero()) {
  224. throw DivisionByZeroException::divisionByZero();
  225. }
  226. if ($scale === null) {
  227. $scale = $this->scale;
  228. } elseif ($scale < 0) {
  229. throw new \InvalidArgumentException('Scale cannot be negative.');
  230. }
  231. if ($that->value === '1' && $that->scale === 0 && $scale === $this->scale) {
  232. return $this;
  233. }
  234. $p = $this->valueWithMinScale($that->scale + $scale);
  235. $q = $that->valueWithMinScale($this->scale - $scale);
  236. $result = Calculator::get()->divRound($p, $q, $roundingMode);
  237. return new BigDecimal($result, $scale);
  238. }
  239. /**
  240. * Returns the exact result of the division of this number by the given one.
  241. *
  242. * The scale of the result is automatically calculated to fit all the fraction digits.
  243. *
  244. * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal.
  245. *
  246. * @return BigDecimal The result.
  247. *
  248. * @throws MathException If the divisor is not a valid number, is not convertible to a BigDecimal, is zero,
  249. * or the result yields an infinite number of digits.
  250. */
  251. public function exactlyDividedBy($that) : BigDecimal
  252. {
  253. $that = BigDecimal::of($that);
  254. if ($that->value === '0') {
  255. throw DivisionByZeroException::divisionByZero();
  256. }
  257. [, $b] = $this->scaleValues($this, $that);
  258. $d = \rtrim($b, '0');
  259. $scale = \strlen($b) - \strlen($d);
  260. $calculator = Calculator::get();
  261. foreach ([5, 2] as $prime) {
  262. for (;;) {
  263. $lastDigit = (int) $d[-1];
  264. if ($lastDigit % $prime !== 0) {
  265. break;
  266. }
  267. $d = $calculator->divQ($d, (string) $prime);
  268. $scale++;
  269. }
  270. }
  271. return $this->dividedBy($that, $scale)->stripTrailingZeros();
  272. }
  273. /**
  274. * Returns this number exponentiated to the given value.
  275. *
  276. * The result has a scale of `$this->scale * $exponent`.
  277. *
  278. * @param int $exponent The exponent.
  279. *
  280. * @return BigDecimal The result.
  281. *
  282. * @throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
  283. */
  284. public function power(int $exponent) : BigDecimal
  285. {
  286. if ($exponent === 0) {
  287. return BigDecimal::one();
  288. }
  289. if ($exponent === 1) {
  290. return $this;
  291. }
  292. if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
  293. throw new \InvalidArgumentException(\sprintf(
  294. 'The exponent %d is not in the range 0 to %d.',
  295. $exponent,
  296. Calculator::MAX_POWER
  297. ));
  298. }
  299. return new BigDecimal(Calculator::get()->pow($this->value, $exponent), $this->scale * $exponent);
  300. }
  301. /**
  302. * Returns the quotient of the division of this number by this given one.
  303. *
  304. * The quotient has a scale of `0`.
  305. *
  306. * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal.
  307. *
  308. * @return BigDecimal The quotient.
  309. *
  310. * @throws MathException If the divisor is not a valid decimal number, or is zero.
  311. */
  312. public function quotient($that) : BigDecimal
  313. {
  314. $that = BigDecimal::of($that);
  315. if ($that->isZero()) {
  316. throw DivisionByZeroException::divisionByZero();
  317. }
  318. $p = $this->valueWithMinScale($that->scale);
  319. $q = $that->valueWithMinScale($this->scale);
  320. $quotient = Calculator::get()->divQ($p, $q);
  321. return new BigDecimal($quotient, 0);
  322. }
  323. /**
  324. * Returns the remainder of the division of this number by this given one.
  325. *
  326. * The remainder has a scale of `max($this->scale, $that->scale)`.
  327. *
  328. * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal.
  329. *
  330. * @return BigDecimal The remainder.
  331. *
  332. * @throws MathException If the divisor is not a valid decimal number, or is zero.
  333. */
  334. public function remainder($that) : BigDecimal
  335. {
  336. $that = BigDecimal::of($that);
  337. if ($that->isZero()) {
  338. throw DivisionByZeroException::divisionByZero();
  339. }
  340. $p = $this->valueWithMinScale($that->scale);
  341. $q = $that->valueWithMinScale($this->scale);
  342. $remainder = Calculator::get()->divR($p, $q);
  343. $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
  344. return new BigDecimal($remainder, $scale);
  345. }
  346. /**
  347. * Returns the quotient and remainder of the division of this number by the given one.
  348. *
  349. * The quotient has a scale of `0`, and the remainder has a scale of `max($this->scale, $that->scale)`.
  350. *
  351. * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal.
  352. *
  353. * @return BigDecimal[] An array containing the quotient and the remainder.
  354. *
  355. * @throws MathException If the divisor is not a valid decimal number, or is zero.
  356. */
  357. public function quotientAndRemainder($that) : array
  358. {
  359. $that = BigDecimal::of($that);
  360. if ($that->isZero()) {
  361. throw DivisionByZeroException::divisionByZero();
  362. }
  363. $p = $this->valueWithMinScale($that->scale);
  364. $q = $that->valueWithMinScale($this->scale);
  365. [$quotient, $remainder] = Calculator::get()->divQR($p, $q);
  366. $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
  367. $quotient = new BigDecimal($quotient, 0);
  368. $remainder = new BigDecimal($remainder, $scale);
  369. return [$quotient, $remainder];
  370. }
  371. /**
  372. * Returns the square root of this number, rounded down to the given number of decimals.
  373. *
  374. * @param int $scale
  375. *
  376. * @return BigDecimal
  377. *
  378. * @throws \InvalidArgumentException If the scale is negative.
  379. * @throws NegativeNumberException If this number is negative.
  380. */
  381. public function sqrt(int $scale) : BigDecimal
  382. {
  383. if ($scale < 0) {
  384. throw new \InvalidArgumentException('Scale cannot be negative.');
  385. }
  386. if ($this->value === '0') {
  387. return new BigDecimal('0', $scale);
  388. }
  389. if ($this->value[0] === '-') {
  390. throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
  391. }
  392. $value = $this->value;
  393. $addDigits = 2 * $scale - $this->scale;
  394. if ($addDigits > 0) {
  395. // add zeros
  396. $value .= \str_repeat('0', $addDigits);
  397. } elseif ($addDigits < 0) {
  398. // trim digits
  399. if (-$addDigits >= \strlen($this->value)) {
  400. // requesting a scale too low, will always yield a zero result
  401. return new BigDecimal('0', $scale);
  402. }
  403. $value = \substr($value, 0, $addDigits);
  404. }
  405. $value = Calculator::get()->sqrt($value);
  406. return new BigDecimal($value, $scale);
  407. }
  408. /**
  409. * Returns a copy of this BigDecimal with the decimal point moved $n places to the left.
  410. *
  411. * @param int $n
  412. *
  413. * @return BigDecimal
  414. */
  415. public function withPointMovedLeft(int $n) : BigDecimal
  416. {
  417. if ($n === 0) {
  418. return $this;
  419. }
  420. if ($n < 0) {
  421. return $this->withPointMovedRight(-$n);
  422. }
  423. return new BigDecimal($this->value, $this->scale + $n);
  424. }
  425. /**
  426. * Returns a copy of this BigDecimal with the decimal point moved $n places to the right.
  427. *
  428. * @param int $n
  429. *
  430. * @return BigDecimal
  431. */
  432. public function withPointMovedRight(int $n) : BigDecimal
  433. {
  434. if ($n === 0) {
  435. return $this;
  436. }
  437. if ($n < 0) {
  438. return $this->withPointMovedLeft(-$n);
  439. }
  440. $value = $this->value;
  441. $scale = $this->scale - $n;
  442. if ($scale < 0) {
  443. if ($value !== '0') {
  444. $value .= \str_repeat('0', -$scale);
  445. }
  446. $scale = 0;
  447. }
  448. return new BigDecimal($value, $scale);
  449. }
  450. /**
  451. * Returns a copy of this BigDecimal with any trailing zeros removed from the fractional part.
  452. *
  453. * @return BigDecimal
  454. */
  455. public function stripTrailingZeros() : BigDecimal
  456. {
  457. if ($this->scale === 0) {
  458. return $this;
  459. }
  460. $trimmedValue = \rtrim($this->value, '0');
  461. if ($trimmedValue === '') {
  462. return BigDecimal::zero();
  463. }
  464. $trimmableZeros = \strlen($this->value) - \strlen($trimmedValue);
  465. if ($trimmableZeros === 0) {
  466. return $this;
  467. }
  468. if ($trimmableZeros > $this->scale) {
  469. $trimmableZeros = $this->scale;
  470. }
  471. $value = \substr($this->value, 0, -$trimmableZeros);
  472. $scale = $this->scale - $trimmableZeros;
  473. return new BigDecimal($value, $scale);
  474. }
  475. /**
  476. * Returns the absolute value of this number.
  477. *
  478. * @return BigDecimal
  479. */
  480. public function abs() : BigDecimal
  481. {
  482. return $this->isNegative() ? $this->negated() : $this;
  483. }
  484. /**
  485. * Returns the negated value of this number.
  486. *
  487. * @return BigDecimal
  488. */
  489. public function negated() : BigDecimal
  490. {
  491. return new BigDecimal(Calculator::get()->neg($this->value), $this->scale);
  492. }
  493. /**
  494. * {@inheritdoc}
  495. */
  496. public function compareTo($that) : int
  497. {
  498. $that = BigNumber::of($that);
  499. if ($that instanceof BigInteger) {
  500. $that = $that->toBigDecimal();
  501. }
  502. if ($that instanceof BigDecimal) {
  503. [$a, $b] = $this->scaleValues($this, $that);
  504. return Calculator::get()->cmp($a, $b);
  505. }
  506. return - $that->compareTo($this);
  507. }
  508. /**
  509. * {@inheritdoc}
  510. */
  511. public function getSign() : int
  512. {
  513. return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
  514. }
  515. /**
  516. * @return BigInteger
  517. */
  518. public function getUnscaledValue() : BigInteger
  519. {
  520. return BigInteger::create($this->value);
  521. }
  522. /**
  523. * @return int
  524. */
  525. public function getScale() : int
  526. {
  527. return $this->scale;
  528. }
  529. /**
  530. * Returns a string representing the integral part of this decimal number.
  531. *
  532. * Example: `-123.456` => `-123`.
  533. *
  534. * @return string
  535. */
  536. public function getIntegralPart() : string
  537. {
  538. if ($this->scale === 0) {
  539. return $this->value;
  540. }
  541. $value = $this->getUnscaledValueWithLeadingZeros();
  542. return \substr($value, 0, -$this->scale);
  543. }
  544. /**
  545. * Returns a string representing the fractional part of this decimal number.
  546. *
  547. * If the scale is zero, an empty string is returned.
  548. *
  549. * Examples: `-123.456` => '456', `123` => ''.
  550. *
  551. * @return string
  552. */
  553. public function getFractionalPart() : string
  554. {
  555. if ($this->scale === 0) {
  556. return '';
  557. }
  558. $value = $this->getUnscaledValueWithLeadingZeros();
  559. return \substr($value, -$this->scale);
  560. }
  561. /**
  562. * Returns whether this decimal number has a non-zero fractional part.
  563. *
  564. * @return bool
  565. */
  566. public function hasNonZeroFractionalPart() : bool
  567. {
  568. return $this->getFractionalPart() !== \str_repeat('0', $this->scale);
  569. }
  570. /**
  571. * {@inheritdoc}
  572. */
  573. public function toBigInteger() : BigInteger
  574. {
  575. $zeroScaleDecimal = $this->scale === 0 ? $this : $this->dividedBy(1, 0);
  576. return BigInteger::create($zeroScaleDecimal->value);
  577. }
  578. /**
  579. * {@inheritdoc}
  580. */
  581. public function toBigDecimal() : BigDecimal
  582. {
  583. return $this;
  584. }
  585. /**
  586. * {@inheritdoc}
  587. */
  588. public function toBigRational() : BigRational
  589. {
  590. $numerator = BigInteger::create($this->value);
  591. $denominator = BigInteger::create('1' . \str_repeat('0', $this->scale));
  592. return BigRational::create($numerator, $denominator, false);
  593. }
  594. /**
  595. * {@inheritdoc}
  596. */
  597. public function toScale(int $scale, int $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
  598. {
  599. if ($scale === $this->scale) {
  600. return $this;
  601. }
  602. return $this->dividedBy(BigDecimal::one(), $scale, $roundingMode);
  603. }
  604. /**
  605. * {@inheritdoc}
  606. */
  607. public function toInt() : int
  608. {
  609. return $this->toBigInteger()->toInt();
  610. }
  611. /**
  612. * {@inheritdoc}
  613. */
  614. public function toFloat() : float
  615. {
  616. return (float) (string) $this;
  617. }
  618. /**
  619. * {@inheritdoc}
  620. */
  621. public function __toString() : string
  622. {
  623. if ($this->scale === 0) {
  624. return $this->value;
  625. }
  626. $value = $this->getUnscaledValueWithLeadingZeros();
  627. return \substr($value, 0, -$this->scale) . '.' . \substr($value, -$this->scale);
  628. }
  629. /**
  630. * This method is required for serializing the object and SHOULD NOT be accessed directly.
  631. *
  632. * @internal
  633. *
  634. * @return array{value: string, scale: int}
  635. */
  636. public function __serialize(): array
  637. {
  638. return ['value' => $this->value, 'scale' => $this->scale];
  639. }
  640. /**
  641. * This method is only here to allow unserializing the object and cannot be accessed directly.
  642. *
  643. * @internal
  644. * @psalm-suppress RedundantPropertyInitializationCheck
  645. *
  646. * @param array{value: string, scale: int} $data
  647. *
  648. * @return void
  649. *
  650. * @throws \LogicException
  651. */
  652. public function __unserialize(array $data): void
  653. {
  654. if (isset($this->value)) {
  655. throw new \LogicException('__unserialize() is an internal function, it must not be called directly.');
  656. }
  657. $this->value = $data['value'];
  658. $this->scale = $data['scale'];
  659. }
  660. /**
  661. * This method is required by interface Serializable and SHOULD NOT be accessed directly.
  662. *
  663. * @internal
  664. *
  665. * @return string
  666. */
  667. public function serialize() : string
  668. {
  669. return $this->value . ':' . $this->scale;
  670. }
  671. /**
  672. * This method is only here to implement interface Serializable and cannot be accessed directly.
  673. *
  674. * @internal
  675. * @psalm-suppress RedundantPropertyInitializationCheck
  676. *
  677. * @param string $value
  678. *
  679. * @return void
  680. *
  681. * @throws \LogicException
  682. */
  683. public function unserialize($value) : void
  684. {
  685. if (isset($this->value)) {
  686. throw new \LogicException('unserialize() is an internal function, it must not be called directly.');
  687. }
  688. [$value, $scale] = \explode(':', $value);
  689. $this->value = $value;
  690. $this->scale = (int) $scale;
  691. }
  692. /**
  693. * Puts the internal values of the given decimal numbers on the same scale.
  694. *
  695. * @param BigDecimal $x The first decimal number.
  696. * @param BigDecimal $y The second decimal number.
  697. *
  698. * @return array{string, string} The scaled integer values of $x and $y.
  699. */
  700. private function scaleValues(BigDecimal $x, BigDecimal $y) : array
  701. {
  702. $a = $x->value;
  703. $b = $y->value;
  704. if ($b !== '0' && $x->scale > $y->scale) {
  705. $b .= \str_repeat('0', $x->scale - $y->scale);
  706. } elseif ($a !== '0' && $x->scale < $y->scale) {
  707. $a .= \str_repeat('0', $y->scale - $x->scale);
  708. }
  709. return [$a, $b];
  710. }
  711. /**
  712. * @param int $scale
  713. *
  714. * @return string
  715. */
  716. private function valueWithMinScale(int $scale) : string
  717. {
  718. $value = $this->value;
  719. if ($this->value !== '0' && $scale > $this->scale) {
  720. $value .= \str_repeat('0', $scale - $this->scale);
  721. }
  722. return $value;
  723. }
  724. /**
  725. * Adds leading zeros if necessary to the unscaled value to represent the full decimal number.
  726. *
  727. * @return string
  728. */
  729. private function getUnscaledValueWithLeadingZeros() : string
  730. {
  731. $value = $this->value;
  732. $targetLength = $this->scale + 1;
  733. $negative = ($value[0] === '-');
  734. $length = \strlen($value);
  735. if ($negative) {
  736. $length--;
  737. }
  738. if ($length >= $targetLength) {
  739. return $this->value;
  740. }
  741. if ($negative) {
  742. $value = \substr($value, 1);
  743. }
  744. $value = \str_pad($value, $targetLength, '0', STR_PAD_LEFT);
  745. if ($negative) {
  746. $value = '-' . $value;
  747. }
  748. return $value;
  749. }
  750. }