You are here

public function Rounder::round in Price 8

Same name and namespace in other branches
  1. 3.x src/Rounder.php \Drupal\price\Rounder::round()
  2. 2.0.x src/Rounder.php \Drupal\price\Rounder::round()
  3. 2.x src/Rounder.php \Drupal\price\Rounder::round()
  4. 3.0.x src/Rounder.php \Drupal\price\Rounder::round()

Rounds the given price to its currency precision.

For example, USD prices will be rounded to 2 decimals.

Parameters

\Drupal\price\Price $price: The price.

int $mode: The rounding mode. One of the following constants: PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, PHP_ROUND_HALF_ODD.

Return value

\Drupal\price\Price The rounded price.

Throws

\InvalidArgumentException When given a price with an unknown currency.

Overrides RounderInterface::round

File

src/Rounder.php, line 29

Class

Rounder

Namespace

Drupal\price

Code

public function round(Price $price, $mode = PHP_ROUND_HALF_UP) {
  $currency_code = $price
    ->getCurrencyCode();

  /** @var \Drupal\price\Entity\CurrencyInterface $currency */
  $currency = $this->currencyStorage
    ->load($currency_code);
  if (!$currency) {
    throw new \InvalidArgumentException(sprintf('Could not load the "%s" currency.', $currency_code));
  }
  $rounded_number = Calculator::round($price
    ->getNumber(), $currency
    ->getFractionDigits(), $mode);
  return new Price($rounded_number, $currency_code);
}