Skip to content

Novis\Intl\NumberFormat::decimal

Writes numbers with the separators of a language and region.

NumberFormat::decimal returns one string for each number, in the same order as the list. The locale you pass, such as "en" or "de", decides the separators. English writes 1,234.5. German writes 1.234,5.

By default the result has up to 3 fraction digits, and the digits are grouped. The options change this. minFractionDigits and maxFractionDigits set how many fraction digits the result has, from 0 to 20. grouping: false turns the group separators off. A number is rounded half away from zero.

The list may mix int, float and decimal values. A decimal keeps every digit it has.

NumberFormat::decimal throws a RuntimeError when a float is not finite, such as Core\Math::INFINITY. It throws a LogicError when the locale tag or an option is not valid.

Good to know: the whole list is formatted in one call. To format one number, pass a list with one number.

Parameters

  • $numbersarray<int|float|decimal>
  • $localestring
  • $options?DigitOptionsdefault null

Return value

Returns array<string>.

Examples

Prices in two languages

<?nvs
// Shows how the same numbers are written in English and in German.
use Novis\Intl\NumberFormat;
array<int|float|decimal> $totals = [1234567.891, 19.9, 42];
// English groups digits with a comma. This prints 1,234,567.891 | 19.9 | 42.
echo Core\Str::join(NumberFormat::decimal($totals, 'en'), ' | '), "\n";
// German groups digits with a period. This prints 1.234.567,891 | 19,9 | 42.
echo Core\Str::join(NumberFormat::decimal($totals, 'de'), ' | '), "\n";
Output
1,234,567.891 | 19.9 | 42
1.234.567,891 | 19,9 | 42

Always two fraction digits

<?nvs
// Shows how to write every number with exactly two fraction digits and no group separators.
use Novis\Intl\NumberFormat;
array<int|float|decimal> $weights = [1250, 3.5, 0.125];
// The minimum and the maximum are both 2. This prints 1250.00, 3.50, 0.13.
echo Core\Str::join(NumberFormat::decimal($weights, 'en', { minFractionDigits: 2, maxFractionDigits: 2, grouping: false }), ', '), "\n";
Output
1250.00, 3.50, 0.13

A decimal keeps every digit

<?nvs
// Shows that a `decimal` value is written with every digit it has.
use Novis\Intl\NumberFormat;
decimal $balance = '98765432109876543.21' as decimal;
// A float cannot store this number exactly. A `decimal` can.
// This prints 98,765,432,109,876,543.21.
echo NumberFormat::decimal([$balance], 'en', { maxFractionDigits: 2 })[0], "\n";
Output
98,765,432,109,876,543.21