Introducing the Laravel Number Helpers

Last updated on by

Hello everyone, Caen here! I'm excited to share with you a recent addition I made to the Laravel framework (PR #48845) that I believe will simplify your number formatting needs. I've introduced a new Number utility class that provides several new helpers to format numbers, and it should be available in the next Laravel release this week.

As another bonus: the helpers are locale-aware, so you can format numbers according to the current locale, either globally, or on a per-method basis!

Background

In many applications, there's often a need to format numbers according to different requirements, such as displaying them as currency, percentages, or human-readable file sizes. Laravel didn't have a dedicated utility for this, so with the help of the community, I decided to create one. I've been working on this utility class for a a little while now, and am really excited that it was merged into the framework. Let's take a look at what it offers.

The Laravel Number Class

Introduction

All methods are part of the Illuminate\Support\Number class:

use Illuminate\Support\Number;

General number formatting

Using the format method, we can format a number according to the current locale.

Number::format(25) // 25
Number::format(100000) // 100,000
Number::format(123456789) // 123,456,789

We can also specify a custom locale to format the number according to that locale's rules.

Number::format(123456789, locale: 'en') // 123,456,789
Number::format(123456789, locale: 'de') // 123.456.789
Number::format(123456789, locale: 'sv') // 123 456 789

Percentage formatting

The formatPercentage method formats a number as a percentage according to the current locale.

Number::percentage(25) // 25%
Number::percentage((1/3) * 100, precision: 2) // 33.33%

Currency formatting

Here's another fun method used to format various currencies with locale support. Perfect for your webshops!

Number::toCurrency(10) // $10.00
Number::toCurrency(25, currency: 'EUR') // €25.00
Number::toCurrency(5.49, currency: 'EUR', locale: 'de') // 5.49 €

File size formatting

Here is the toFileSize method which actually is the whole reason behind this utility class. I first submitted a PR to add a File::bytesToHuman() helper (PR #48827), which Taylor then suggested we add as part of a new Number class.

Number::toFileSize(1024); // 1 KB
Number::toFileSize(1600, precision: 2); // 1.56 KB
Number::toFileSize(1024 * 1024 * 1024 * 5); // 5 GB

Human readable formatting

Next up is also a quite fun one for when you want something that's more readable than precise. It converts numbers to a human-readable string.

Number::forHumans(1000) // 1 thousand
Number::forHumans(12345) // 12 thousand
Number::forHumans(12345, precision: 3) // 12.345 thousand

Setting the locale

We can set the locale globally using the setLocale method, for example in a service provider:

Number::setLocale('sv');

You can also use the withLocale method which executes the given callback using the specified locale and then restores the original locale:

Number::withLocale('sv', function () {
return Number::format(123456789);
});

Conclusion

I hope this new addition makes your life a bit easier when dealing with number formatting in Laravel. Please free to check out the next Laravel release and incorporate this utility class into your projects. Happy coding!

Update 11/21/2023: The Numbers helper is now documented in the official Laravel helpers documentation.

Caen De Silva photo

Background in freelance frontend, currently a fullstack Laravel/PHP engineer with a strong focus on backend and cybersecurity and a passion for Open Source. Created Laravel-based static site generator HydePHP.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and more

Visit CodeRabbit
Curotec logo

Curotec

Hire the top Latin American Laravel talent. Flexible engagements, budget optimized, and quality engineering.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Generate Documentation in Laravel with AI image

Generate Documentation in Laravel with AI

Read article
Customizing Laravel Optimization with --except image

Customizing Laravel Optimization with --except

Read article
Solo Dumps for Laravel image

Solo Dumps for Laravel

Read article
Download Files Easily with Laravel's HTTP sink Method image

Download Files Easily with Laravel's HTTP sink Method

Read article
Aureus ERP image

Aureus ERP

Read article
Precise Collection Filtering with Laravel's whereNotInStrict image

Precise Collection Filtering with Laravel's whereNotInStrict

Read article