Merge pull request #5226 from davecivicrm/CRM-15578
[civicrm-core.git] / CRM / Utils / Number.php
CommitLineData
ac5f2ccd 1<?php
5bc392e6
EM
2
3/**
4 * Class CRM_Utils_Number
5 */
ac5f2ccd
TO
6class CRM_Utils_Number {
7 /**
fe482240 8 * Create a random number with a given precision.
ac5f2ccd 9 *
77855840
TO
10 * @param array $precision
11 * (int $significantDigits, int $postDecimalDigits).
f4aaa82a
EM
12 *
13 * @return float
ac5f2ccd
TO
14 * @link https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html
15 */
00be9182 16 public static function createRandomDecimal($precision) {
ac5f2ccd
TO
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
77855840
TO
28 * @param array $precision
29 * (int $significantDigits, int $postDecimalDigits).
ac5f2ccd
TO
30 * @return float
31 * @link https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html
32 */
00be9182 33 public static function createTruncatedDecimal($keyValue, $precision) {
ac5f2ccd
TO
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 }
96025800 48
f4aaa82a 49}