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