Format Numbers with Laravel's Number Helper
Number formatting often ends up scattered throughout an application.
You might have:
number_format($price, 2);
in one place and custom formatting logic somewhere else.
Laravel's Number helper provides a cleaner API for common number-formatting tasks.
Format a Number
use Illuminate\Support\Number;
Number::format(1234567.89);
You can control the number of decimal places:
Number::format(1234567.89, 2);
This gives you a consistent way to format numbers throughout your application.
Format Currency
For prices, you can use:
Number::currency(2500);
You can also specify the currency:
Number::currency(2500, 'USD');
For example, this is useful when displaying product prices, invoices, or payment amounts.
Format Percentages
Laravel also provides percentage formatting:
Number::percentage(75);
You can specify decimal precision when needed:
Number::percentage(75.25, 2);
This can be useful for dashboards, reports, and analytics.
Make Large Numbers Easier to Read
For large values, you can use:
Number::abbreviate(1234567);
Instead of displaying a long number, Laravel can present it in a more compact format.