1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SilverCommerce\TaxAdmin\Helpers; |
4
|
|
|
|
5
|
|
|
use SilverStripe\Core\Config\Config; |
6
|
|
|
use SilverStripe\Core\Config\Configurable; |
7
|
|
|
use SilverStripe\Core\Injector\Injectable; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Simple helper class to provide generic functions to help with |
11
|
|
|
* maths functions |
12
|
|
|
*/ |
13
|
|
|
class MathsHelper |
14
|
|
|
{ |
15
|
|
|
use Injectable; |
16
|
|
|
use Configurable; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Round all numbers down globally |
20
|
|
|
* |
21
|
|
|
* @var boolean |
22
|
|
|
*/ |
23
|
|
|
private static $round_down = true; |
|
|
|
|
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Rounds up a float to a specified number of decimal places |
27
|
|
|
* (basically acts like ceil() but allows for decimal places) |
28
|
|
|
* |
29
|
|
|
* @param float $value Float to round up |
30
|
|
|
* @param int $places the number of decimal places to round to |
31
|
|
|
* |
32
|
|
|
* @return float |
33
|
|
|
*/ |
34
|
|
|
public static function round_up($value, $places = 0) |
35
|
|
|
{ |
36
|
|
|
return self::round($value, $places, false); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Rounds up a float to a specified number of decimal places |
41
|
|
|
* (basically acts like ceil() but allows for decimal places) |
42
|
|
|
* |
43
|
|
|
* @param float $value Float to round up |
44
|
|
|
* @param int $places the number of decimal places to round to |
45
|
|
|
* |
46
|
|
|
* @return float |
47
|
|
|
*/ |
48
|
|
|
public static function round_down($value, $places = 0) |
49
|
|
|
{ |
50
|
|
|
return self::round($value, $places, true); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Round the provided value to the defined number of places in the direction |
55
|
|
|
* provided (up or down). |
56
|
|
|
* |
57
|
|
|
* @param float $value The value we want to round |
58
|
|
|
* @param int $places The number of decimal places to round to |
59
|
|
|
* @param boolean $down Do we round down? If false value will be rounded up |
60
|
|
|
* |
61
|
|
|
* @return float |
62
|
|
|
*/ |
63
|
|
|
public static function round($value, $places = 0, $down = null, $negatives = false) |
|
|
|
|
64
|
|
|
{ |
65
|
|
|
if (empty($down)) { |
66
|
|
|
$down = Config::inst()->get(self::class, "round_down"); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$offset = 0; |
70
|
|
|
|
71
|
|
|
// If we are rounding to decimals get a more granular number. |
72
|
|
|
if ($places !== 0) { |
73
|
|
|
if ($down) { |
74
|
|
|
$offset = -0.45; |
75
|
|
|
} else { |
76
|
|
|
$offset = 0.45; |
77
|
|
|
} |
78
|
|
|
$offset /= pow(10, $places); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
$return = round( |
82
|
|
|
$value + $offset, |
83
|
|
|
$places, |
84
|
|
|
PHP_ROUND_HALF_UP |
85
|
|
|
); |
86
|
|
|
|
87
|
|
|
return $return; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|