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