Commit | Line | Data |
---|---|---|
ac5f2ccd | 1 | <?php |
5bc392e6 EM |
2 | |
3 | /** | |
4 | * Class CRM_Utils_Number | |
5 | */ | |
ac5f2ccd TO |
6 | class CRM_Utils_Number { |
7 | /** | |
8 | * Create a random number with a given precision | |
9 | * | |
10 | * @param array $precision (int $significantDigits, int $postDecimalDigits) | |
f4aaa82a EM |
11 | * |
12 | * @return float | |
ac5f2ccd TO |
13 | * @link https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html |
14 | */ | |
15 | static function createRandomDecimal($precision) { | |
16 | list ($sigFigs, $decFigs) = $precision; | |
17 | $rand = rand(0, pow(10, $sigFigs) - 1); | |
18 | return $rand / pow(10, $decFigs); | |
19 | } | |
20 | ||
21 | /** | |
22 | * Given a number, coerce it to meet the precision requirement. If possible, it should | |
23 | * keep the number as-is. If necessary, this may drop the least-significant digits | |
24 | * and/or move the decimal place. | |
25 | * | |
26 | * @param int|float $keyValue | |
27 | * @param array $precision (int $significantDigits, int $postDecimalDigits) | |
28 | * @return float | |
29 | * @link https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html | |
30 | */ | |
31 | static function createTruncatedDecimal($keyValue, $precision) { | |
32 | list ($sigFigs, $decFigs) = $precision; | |
33 | $sign = ($keyValue < 0) ? '-1' : 1; | |
34 | $val = str_replace('.', '', abs($keyValue)); // ex: -123.456 ==> 123456 | |
35 | $val = substr($val, 0, $sigFigs); // ex: 123456 => 1234 | |
36 | ||
37 | // Move any extra digits after decimal | |
38 | $extraFigs = strlen($val) - ($sigFigs - $decFigs); | |
39 | if ($extraFigs > 0) { | |
40 | return $sign * $val / pow(10, $extraFigs); // ex: 1234 => 1.234 | |
41 | } | |
42 | else { | |
43 | return $sign * $val; | |
44 | } | |
45 | } | |
f4aaa82a | 46 | } |