4 * Class CRM_Utils_Number
6 class CRM_Utils_Number
{
8 * Create a random number with a given precision
10 * @param array $precision
11 * (int $significantDigits, int $postDecimalDigits).
14 * @link https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html
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);
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.
27 * @param int|float $keyValue
28 * @param array $precision
29 * (int $significantDigits, int $postDecimalDigits).
31 * @link https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html
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
39 // Move any extra digits after decimal
40 $extraFigs = strlen($val) - ($sigFigs - $decFigs);
42 return $sign * $val / pow(10, $extraFigs); // ex: 1234 => 1.234