4

I am using the filter localizedcurrency to format a price in a multi language website. Since this is the price of houses, I don't need the decimal part.

I can't find out how to hide it, besides using the replace filter. I wonder if there is a better way, because using replace would mean I have to replace a dot in english and a comma in french and so on...

I also can't use some form of substr because the dollar sign can be before or after the value.

I tried passing an int instead of a float to the filter, but it just defaults to .00

Thanks!

Oylex
  • 314
  • 5
  • 20

1 Answers1

5

use money_format:

    setlocale(LC_MONETARY, 'en_US');
    echo money_format('%.0i', $number);

The .0 in '%.0i' is the right side precision.

You might need to add a filter to your twig extension. Let me know if you need help with that.

Edit:

Looking into intl extension, it seems to call formatCurrency method from NumberFormatter class, which in turn calls a private roundCurrency, which eventually does:

private function roundCurrency($value, $currency)
{
    $fractionDigits = Intl::getCurrencyBundle()->getFractionDigits($currency);

    // ...

    // Round with the formatter rounding mode
    $value = $this->round($value, $fractionDigits);

    // ...
}

But trying to trace where $fractionDigits value comes from will go another 2 classes up the hierarchy, and become something as mystic as this:

public function getFractionDigits($currency)
{
    try {
        return $this->reader->readEntry($this->path, 'meta', array('Meta', $currency, static::INDEX_FRACTION_DIGITS));
    } catch (MissingResourceException $e) {
        return $this->reader->readEntry($this->path, 'meta', array('Meta', 'DEFAULT', static::INDEX_FRACTION_DIGITS));
    }
}

So it might be possible to get your current extension to do the rounding, but I would probably go with my own filter as it seems to be easier and i can specify precision on the fly.

Karolis
  • 2,580
  • 2
  • 16
  • 31