Skip to content

Novis\Intl\NumberFormat::currency

Writes amounts of money, the way a language and region write them.

NumberFormat::currency returns one string for each amount, in the same order as the list. The second argument is the currency, as its three-letter ISO 4217 code, such as "EUR" or "USD". The locale decides where the symbol goes and which separators are used. In English, 1234.5 euros is €1,234.50. In German, it is 1.234,50 €.

Each amount is rounded to the digits the currency uses: 2 for euros and dollars, none for yen. The display option chooses how the currency is shown. NumberFormat::CurrencyDisplay::Symbol is the default and writes €. NumberFormat::CurrencyDisplay::Narrow writes the shortest symbol. NumberFormat::CurrencyDisplay::Name writes the name, such as 2.00 euros.

NumberFormat::currency throws a LogicError when the currency code does not have three letters, or when the locale tag is not valid. It throws a RuntimeError when a float is not finite.

Good to know: a float cannot store most amounts of cents exactly. Use decimal values for money, and the amount you pass is the amount that is written.

Parameters

  • $amountsarray<int|float|decimal>
  • $currencystring
  • $localestring
  • $options?{ display?: CurrencyDisplay }default null

Return value

Returns array<string>.

Examples

A price in euros

<?nvs
// Shows how to write a price in euros for an English reader and for a German reader.
use Novis\Intl\NumberFormat;
decimal $price = '1234.5' as decimal;
// English puts the symbol first. This prints €1,234.50.
echo NumberFormat::currency([$price], 'EUR', 'en')[0], "\n";
// German puts the symbol last, after a space. This prints 1.234,50 €.
echo NumberFormat::currency([$price], 'EUR', 'de')[0], "\n";
Output
€1,234.50
1.234,50 €

Each currency has its own digits

<?nvs
// Shows that each currency is rounded to the digits it uses.
use Novis\Intl\NumberFormat;
array<int|float|decimal> $amounts = [1234.5, 3];
// Dollars have 2 fraction digits. This prints $1,234.50 | $3.00.
echo Core\Str::join(NumberFormat::currency($amounts, 'USD', 'en'), ' | '), "\n";
// Yen have none, so 1234.5 is rounded. This prints ¥1,235 | ¥3.
echo Core\Str::join(NumberFormat::currency($amounts, 'JPY', 'en'), ' | '), "\n";
Output
$1,234.50 | $3.00
¥1,235 | ¥3

The currency name

<?nvs
// Shows how to write the name of the currency instead of its symbol.
use Novis\Intl\NumberFormat;
// This prints 2.00 US dollars.
echo NumberFormat::currency([2], 'USD', 'en', { display: NumberFormat::CurrencyDisplay::Name })[0], "\n";
// This prints 1.00 euros.
echo NumberFormat::currency([1], 'EUR', 'en', { display: NumberFormat::CurrencyDisplay::Name })[0], "\n";
Output
2.00 US dollars
1.00 euros