When formatting money strings, by default only show the trailing digits that are not zero.

This commit is contained in:
Jan Böhmer 2019-09-01 14:08:53 +02:00
parent 3ab53ba863
commit 8a80474b3a
2 changed files with 13 additions and 7 deletions

View file

@ -48,12 +48,14 @@ class MoneyFormatter
} }
/** /**
* @param string $value The value that should be * Format the the given value in the given currency
* @param Currency|null $currency * @param string|float $value The value that should be formatted.
* @param int $decimals * @param Currency|null $currency The currency that should be used for formatting. If null the global one is used
* @param int $decimals The number of decimals that should be shown.
* @param bool $show_all_digits If set to true, all digits are shown, even if they are null.
* @return string * @return string
*/ */
public function format(string $value, ?Currency $currency = null, $decimals = 5) public function format($value, ?Currency $currency = null, $decimals = 5, bool $show_all_digits = false)
{ {
$iso_code = $this->base_currency; $iso_code = $this->base_currency;
if ($currency !== null && !empty($currency->getIsoCode())) { if ($currency !== null && !empty($currency->getIsoCode())) {
@ -61,7 +63,11 @@ class MoneyFormatter
} }
$number_formatter = new \NumberFormatter($this->locale, \NumberFormatter::CURRENCY); $number_formatter = new \NumberFormatter($this->locale, \NumberFormatter::CURRENCY);
$number_formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $decimals); if ($show_all_digits) {
$number_formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $decimals);
} else {
$number_formatter->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $decimals);
}
return $number_formatter->formatCurrency((float) $value, $iso_code); return $number_formatter->formatCurrency((float) $value, $iso_code);
} }

View file

@ -130,9 +130,9 @@ class AppExtension extends AbstractExtension
return $this->moneyFormatter->format($amount, $currency, $decimals); return $this->moneyFormatter->format($amount, $currency, $decimals);
} }
public function siFormat($value, $unit, $decimals = 2) public function siFormat($value, $unit, $decimals = 2, bool $show_all_digits = false)
{ {
return $this->siformatter->format($value, $unit, $decimals); return $this->siformatter->format($value, $unit, $decimals, $show_all_digits);
} }
public function amountFormat($value, ?MeasurementUnit $unit, array $options = []) public function amountFormat($value, ?MeasurementUnit $unit, array $options = [])