Novis\Intl\NumberFormat::compact
Novis\Intl\NumberFormat::compact(
array<int|float|decimal> $numbers,
string $locale,
?{ display?: CompactDisplay } $options = null,
): array<string>Writes large numbers in a short form, the way a language and region write them.
NumberFormat::compact returns one string for each number, in the same order as the list. In English, 1234 is 1.2K and 1500000 is 1.5M. A number under one thousand is written as it is. Each language has its own short forms, so the locale decides the result.
The display option chooses the form. NumberFormat::CompactDisplay::Short is the default and writes 1.2K. NumberFormat::CompactDisplay::Long writes the word, such as 1.2 thousand.
NumberFormat::compact throws a RuntimeError when a float is not finite. It throws a LogicError when the locale tag is not valid.
Good to know: the short form is rounded, so it is for reading. Show the full number with NumberFormat::decimal where the reader needs every digit.
Parameters
$numbersarray<int|float|decimal>$localestring$options?{ display?: CompactDisplay }default null
Return value
Returns array<string>.
Examples
Follower counts
<?nvs// Shows how to write follower counts in a short form, as a profile page does.use Novis\Intl\NumberFormat;
array<int|float|decimal> $followers = [999, 1234, 1500000];
// A number under one thousand stays as it is. This prints 999 | 1.2K | 1.5M.echo Core\Str::join(NumberFormat::compact($followers, 'en'), ' | '), "\n";999 | 1.2K | 1.5MThe long form
<?nvs// Shows how to write the word for thousand or million instead of a letter.use Novis\Intl\NumberFormat;
array<int|float|decimal> $views = [1234, 1500000];
// This prints 1.2 thousand | 1.5 million.echo Core\Str::join(NumberFormat::compact($views, 'en', { display: NumberFormat::CompactDisplay::Long }), ' | '), "\n";1.2 thousand | 1.5 millionThe locale changes the short form
<?nvs// Shows that each language has its own short form for large numbers.use Novis\Intl\NumberFormat;
array<int|float|decimal> $downloads = [1500000];
// This prints 1.5M.echo NumberFormat::compact($downloads, 'en')[0], "\n";
// This prints 1,5 Mio.echo NumberFormat::compact($downloads, 'de')[0], "\n";1.5M1,5 Mio.