acme
acme

Reputation: 14856

How to formatting a monetary value with ICU hiding the minor units if zero

I'm trying to format a currency value with Zend's CurrencyFormat (using ICU). Basically it's working - the pattern #,##0.# outputs a correct format like 1.200,00 €.

Is it possible to leave out the minor unit part if it's zero just by modifying the pattern? I want to have the following formatting results:

Upvotes: 0

Views: 474

Answers (1)

SzymonM
SzymonM

Reputation: 904

I don't think it is possible to achieve it by modifying pattern. I mean, you can check if provided number is type of float or int. If it's int you can set different pattern, but there is simpler way (more recommended way IMO).
3rd argument of __invoke() method is $showDecimal. It takes bool value. If you want decimals to be visible- pass true (it's default value), false otherwise.

Example
true - if number is integer

<?php echo $this->currencyFormat(1234, "EUR", true, "de_DE"); ?>

Output:

1.234,00 €

false - if number is float

<?php echo $this->currencyFormat(1234, "EUR", false, "de_DE"); ?>

Output:

1.234 €

Loop example

// $prices = [1234, 1234.23, 234, 3456.54]
<?php foreach($prices as $price): ?>
    <?php $showDecimal = is_float($price) ? true : false;
    <p><?php echo $this->currencyFormat(1234, "EUR", $showDecimal, "de_DE"); ?></p>
<?php endforeach; ?>

Global
If for some reason you want hide decimal numbers for all currencies/formats, you can use setShouldShowDecimals() method:

$this->plugin("currencyformat")->setShouldShowDecimals(false)->setCurrencyCode("USD")->setLocale("en_US");

echo $this->currencyFormat(1234.00);  // "$1,234"

Here is a list of all available symbols for pattern http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#details

Upvotes: 1

Related Questions