You are here

public function Rounder::round in Commerce Core 8.2

Rounds the given price to its currency precision.

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

Parameters

\Drupal\commerce_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\commerce_price\Price The rounded price.

Throws

\InvalidArgumentException When given a price with an unknown currency.

Overrides RounderInterface::round

File

modules/price/src/Rounder.php, line 29

Class

Rounder

Namespace

Drupal\commerce_price

Code

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

  /** @var \Drupal\commerce_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);
}