JBZoo\SimpleTypes\Formatter::round PHP Method

round() public method

public round ( float $value, string $rule, array $params = [] ) : float
$value float
$rule string
$params array
return float
    public function round($value, $rule, array $params = array())
    {
        $format = $this->get($rule);
        // prepare params
        $params = array_merge(array('roundType' => null, 'roundValue' => null), $params);
        // get vars
        $roundType = $params['roundType'];
        $roundValue = $params['roundValue'];
        if (!$roundType) {
            $roundType = array_key_exists('round_type', $format) ? $format['round_type'] : self::ROUND_NONE;
        }
        if (null === $roundValue) {
            $roundValue = array_key_exists('round_value', $format) ? $format['round_value'] : self::ROUND_DEFAULT;
        }
        $roundValue = (int) $roundValue;
        if (self::ROUND_CEIL === $roundType) {
            $base = pow(10, $roundValue);
            $value = ceil($value * $base) / $base;
        } elseif (self::ROUND_CLASSIC === $roundType) {
            $value = round($value, $roundValue);
        } elseif (self::ROUND_FLOOR === $roundType) {
            $base = pow(10, $roundValue);
            $value = floor($value * $base) / $base;
        } elseif (self::ROUND_NONE === $roundType) {
            $value = round($value, Formatter::ROUND_DEFAULT);
            // hack, because 123.400000001 !== 123.4
        } else {
            throw new Exception('Undefined round mode: "' . $roundType . '"');
        }
        return $value;
    }

Usage Example

Beispiel #1
0
 /**
  * @param int    $roundValue
  * @param string $mode
  * @return $this
  * @throws \JBZoo\SimpleTypes\Exception
  */
 public function round($roundValue = null, $mode = Formatter::ROUND_CLASSIC)
 {
     $oldValue = $this->_value;
     $newValue = $this->_formatter->round($this->_value, $this->_rule, array('roundValue' => $roundValue, 'roundType' => $mode));
     $this->log('Rounded (size=' . (int) $roundValue . '; type=' . $mode . ') "' . $oldValue . '" => "' . $newValue . '"');
     $this->_value = $newValue;
     return $this;
 }