2 class CRM_Utils_Number
{
4 * Create a random number with a given precision
6 * @param array $precision (int $significantDigits, int $postDecimalDigits)
9 * @link https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html
11 static function createRandomDecimal($precision) {
12 list ($sigFigs, $decFigs) = $precision;
13 $rand = rand(0, pow(10, $sigFigs) - 1);
14 return $rand / pow(10, $decFigs);
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.
22 * @param int|float $keyValue
23 * @param array $precision (int $significantDigits, int $postDecimalDigits)
25 * @link https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html
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
33 // Move any extra digits after decimal
34 $extraFigs = strlen($val) - ($sigFigs - $decFigs);
36 return $sign * $val / pow(10, $extraFigs); // ex: 1234 => 1.234