Skip to content

Commit

Permalink
Update solution to be closed to the original
Browse files Browse the repository at this point in the history
  • Loading branch information
nfourtythree committed Oct 15, 2024
1 parent eac9852 commit b1e9170
Showing 1 changed file with 8 additions and 13 deletions.
21 changes: 8 additions & 13 deletions src/helpers/Currency.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,22 +106,17 @@ public static function formatAsCurrency($amount, mixed $currency = null, bool $c

if ($format) {
$numberFormatter = new \NumberFormatter(Craft::$app->getFormattingLocale(), \NumberFormatter::CURRENCY);
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, new ISOCurrencies());
$money = Plugin::getInstance()->getCurrencies()->getTeller($currencyIso)->convertToMoney($amount);

$amount = $moneyFormatter->format($money);
}
// Strip zeros if requested and only if the amount won't have any decimal places
if ($stripZeros && (int)$amount == $amount) {
$numberFormatter->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 0);
$numberFormatter->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
}

if ($stripZeros) {
$decimalSeparator = Craft::$app->getFormattingLocale()->getNumberSymbol(\craft\i18n\Locale::SYMBOL_DECIMAL_SEPARATOR);
// find decimal separator and zeros based on formatting locale and number of subunits
$subUnit = Plugin::getInstance()->getCurrencies()->getSubunitFor($currencyIso);
$zeroSymbol = Craft::$app->getFormattingLocale()->getNumberSymbol(\craft\i18n\Locale::SYMBOL_ZERO_DIGIT);
$zerosString = $decimalSeparator . str_repeat($zeroSymbol, $subUnit);
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, new ISOCurrencies());
$money = Plugin::getInstance()->getCurrencies()->getTeller($currencyIso)->convertToMoney($amount);

if (str_contains($amount, $zerosString)) {
$amount = str_replace($zerosString, '', $amount);
}
return $moneyFormatter->format($money);
}

return (string)$amount;
Expand Down

0 comments on commit b1e9170

Please sign in to comment.