4 * Class CRM_Utils_Number
6 class CRM_Utils_Number
{
8 * Create a random number with a given precision
10 * @param array $precision (int $significantDigits, int $postDecimalDigits)
13 * @link https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html
15 static function createRandomDecimal($precision) {
16 list ($sigFigs, $decFigs) = $precision;
17 $rand = rand(0, pow(10, $sigFigs) - 1);
18 return $rand / pow(10, $decFigs);
22 * Given a number, coerce it to meet the precision requirement. If possible, it should
23 * keep the number as-is. If necessary, this may drop the least-significant digits
24 * and/or move the decimal place.
26 * @param int|float $keyValue
27 * @param array $precision (int $significantDigits, int $postDecimalDigits)
29 * @link https://dev.mysql.com/doc/refman/5.1/en/fixed-point-types.html
31 static function createTruncatedDecimal($keyValue, $precision) {
32 list ($sigFigs, $decFigs) = $precision;
33 $sign = ($keyValue < 0) ?
'-1' : 1;
34 $val = str_replace('.', '', abs($keyValue)); // ex: -123.456 ==> 123456
35 $val = substr($val, 0, $sigFigs); // ex: 123456 => 1234
37 // Move any extra digits after decimal
38 $extraFigs = strlen($val) - ($sigFigs - $decFigs);
40 return $sign * $val / pow(10, $extraFigs); // ex: 1234 => 1.234