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