Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The new Number utility in Laravel

PHP has this NumberFormatter class which is a part of the intl extension. This class is used to format numbers based on the locale. I covered this in one of my previous articles.

But in a nutshell, the class consists of numerous methods using which you can format numbers, currencies, and percentages according to the specified or default locale.

Here’s an example.

$human_readable = new \NumberFormatter(
    'en_US', 
    \NumberFormatter::PADDING_POSITION
);

echo $human_readable->format(10000); // 10K

As you can tell, the format method formats the given number according to the locale and returns the formatted number.

Now, in a recent release, Laravel introduces a new Illuminate\Support\Number utility which is basically a wrapper around the NumberFormatter class.

It gives you a fluent interface to format numbers, currencies, and percentages according to the specified or default locale.

Here are all the methods that are available in the Number utility for various formatting purposes.

use Illuminate\Support\Number;

echo Number::format(22678); // 22,678
echo Number::currency(1234.56, 'USD'); // $1,234.56
echo Number::forHumans(19500); // 20 thousand  
echo Number::fileSize(5897); // 6 KB
echo Number::ordinal(10); // 10th
echo Number::percentage(76); // 76%
echo Number::spell(1983); // one thousand nine hundred eighty-three

Now, all the methods accept your preferred locale in which you want to format the number. For instance, if you want to format the number in the fr locale, you can do it like so.

use Illuminate\Support\Number;

echo Number::format(22678, locale: 'fr'); // 22 678

For currencies, you can also specify the currency symbol and the locale like so.

use Illuminate\Support\Number;

echo Number::currency(1234.56, in: 'EUR', locale: 'fr'); // 1 234,56 €

Spell out the number in the locale of your choice like so.

use Illuminate\Support\Number;

echo Number::spell(1983, locale: 'fr'); 
// mille neuf cent quatre-vingt-trois

The same goes for other methods as well.

Apart from this, the Number utility is also macroable. So, you can add your custom methods to your own liking.

Read more about the Number utility in this PR.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?