You are here

public function Intl::formatAmount in Currency 8.3

Formats an amount.

Parameters

\Commercie\Currency\CurrencyInterface $currency: The currency the amount is in.

string $amount: A numeric string.

string $language_type: One of the \Drupal\Core\Language\LanguageInterface\TYPE_* constants.

Return value

string|\Drupal\Core\StringTranslation\TranslatableMarkup

Overrides AmountFormatterInterface::formatAmount

File

modules/currency_intl/src/Plugin/Currency/AmountFormatter/Intl.php, line 58

Class

Intl
Formats amounts using PHP's Intl extension.

Namespace

Drupal\currency_intl\Plugin\Currency\AmountFormatter

Code

public function formatAmount(CurrencyInterface $currency, $amount, $language_type = LanguageInterface::TYPE_CONTENT) {
  $currency_locale = $this->localeDelegator
    ->resolveCurrencyLocale();
  $decimal_position = strpos($amount, '.');
  $number_of_decimals = $decimal_position !== FALSE ? strlen(substr($amount, $decimal_position + 1)) : 0;
  $formatter = new \NumberFormatter($currency_locale
    ->getLocale(), \NumberFormatter::PATTERN_DECIMAL, $currency_locale
    ->getPattern());
  $formatter
    ->setAttribute(\NumberFormatter::FRACTION_DIGITS, $number_of_decimals);
  $formatter
    ->setSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, $currency_locale
    ->getDecimalSeparator());
  $formatter
    ->setSymbol(\NumberFormatter::MONETARY_SEPARATOR_SYMBOL, $currency_locale
    ->getDecimalSeparator());
  $formatter
    ->setSymbol(\NumberFormatter::GROUPING_SEPARATOR_SYMBOL, $currency_locale
    ->getGroupingSeparator());
  $formatter
    ->setSymbol(\NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL, $currency_locale
    ->getGroupingSeparator());
  $formatter
    ->setSymbol(\NumberFormatter::CURRENCY_SYMBOL, $currency
    ->getSign());
  $formatter
    ->setSymbol(\NumberFormatter::INTL_CURRENCY_SYMBOL, $currency
    ->getCurrencyCode());
  return $formatted = $formatter
    ->format($amount);
}