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