skip to Main Content

Trying to format the number as a currency amount and add the relative ISO code as suffix.

$NumberFormatter = new NumberFormatter(MY_LOCALE, NumberFormatter::CURRENCY);
$NumberFormatter->setSymbol(NumberFormatter::CURRENCY_SYMBOL, "");
$NumberFormatter->formatCurrency($Amount, $CurrencyCode="EUR");

This will produce "10,00" if $CurrencyCode=EUR but "10,00 DKK" or "10,00 RUB" for $CurrencyCode=DKK, $CurrencyCode=RUB

Why isn’t it behaving consistently?

I would like it to return just the amount, without currency symbol nor ISO code, so that I can add the ISO code afterwards.

Using PHP 8.2.8 on a Debian.

2

Answers


  1. Chosen as BEST ANSWER
    $Locale = "it_IT";
    $CurrencyCode = "JPY";
    $Amount = 100.50;
    
    $NumberFormatter = new NumberFormatter($Locale, NumberFormatter::CURRENCY);
    $NumberFormatter->setTextAttribute(NumberFormatter::CURRENCY_CODE, $CurrencyCode);
    $NumberFormatter->setSymbol(NumberFormatter::CURRENCY_SYMBOL, "");
    echo $NumberFormatter->format($Amount) ." ". $CurrencyCode;
    

    The above will: a) remove the currency symbol, b) retain the currency-specific number of fraction digits, c) retain the locale-specific fraction digits and thousands separator chars, d) add the ISO currency code after the formatted amount


  2. That’s the point of the NumberFormatter class. It uses a huge set of rules that have been compiled for each Locale. If that locale’s rules say only include the number (for instance, if the locale matches the existing currency), then it will only show that. But if you specify a currency code that does is different, based on the rules, will likely display the currency so the user does not get confused over what currency is being displayed. The rules are based on what a majority of people generally expect as far as formatting currency or numbers in general for the specified locale.

    That being said, if you just want a basic formatted number, you can just use the DECIMAL basic formatter:

    $NumberFormatter = new NumberFormatter(MY_LOCALE, NumberFormatter::DECIMAL);
    $NumberFormatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 2);
    $NumberFormatter->format($Amount); // 10.00 or 10,00; Depending on locale rules
    

    You can then add your own currency symbol and/or codes. However, the way your code was set up was mostly correct and would provide the proper symbol and/or code in the correct locations for the locale. Adding them on your own may confuse people in certain locales.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search