1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\SalesRule\Model;
use Magento\Framework\Pricing\PriceCurrencyInterface;
/**
* Round price and save rounding operation delta.
*/
class DeltaPriceRound
{
/**
* @var PriceCurrencyInterface
*/
private $priceCurrency;
/**
* @var float[]
*/
private $roundingDeltas;
/**
* @param PriceCurrencyInterface $priceCurrency
*/
public function __construct(PriceCurrencyInterface $priceCurrency)
{
$this->priceCurrency = $priceCurrency;
}
/**
* Round price based on previous rounding operation delta.
*
* @param float $price
* @param string $type
* @return float
*/
public function round(float $price, string $type): float
{
if ($price) {
// initialize the delta to a small number to avoid non-deterministic behavior with rounding of 0.5
$delta = isset($this->roundingDeltas[$type]) ? $this->roundingDeltas[$type] : 0.000001;
$price += $delta;
$roundPrice = $this->priceCurrency->round($price);
$this->roundingDeltas[$type] = $price - $roundPrice;
$price = $roundPrice;
}
return $price;
}
/**
* Reset all deltas.
*
* @return void
*/
public function resetAll(): void
{
$this->roundingDeltas = [];
}
/**
* Reset deltas by type.
*
* @param string $type
* @return void
*/
public function reset(string $type): void
{
if (isset($this->roundingDeltas[$type])) {
unset($this->roundingDeltas[$type]);
}
}
}