PHP Number Format Currency – How to Format Currencies in PHP
Written by Kolade Chris | Oct 5, 2024 | #PHP | 5 minutes Read
In eCommerce applications, financial reports, and other apps where currencies are integral, formatting strings or numbers as currency could be a regular task.
You can do this yourself and go through the stress of adapting the apps to several currencies, or take advantage of the built-in methods PHP offers for the same task.
In this article, you’ll learn how to manually format currencies and use the built-in PHP way of doing it more conveniently.
The Manual Approach: How to Format Currency in PHP with a Variable or Custom Function
You can use the number_format()
function as a quick workaround:
For reusability, you could create a function that takes a number or string and converts it to a certain currency:
The problem with this approach is that it handles one currency only.
To fix that, you can go ahead and make it accept a certain currency symbol with an extra parameter:
The problem with this manual approach is that it lacks locale-specific support and dynamic currency symbols, even though the number_format()
function accurately formats numbers.
The approach may also introduce precision issues and complexity with functions like explode
and implode
. In addition, handling invalid input can be cumbersome, and hardcoding currency symbols limit flexibility.
The solution is the NumberFormatter
class from the Intl
extension. Let’s look at how to use it.
How to Format Currencies with the PHP NumberFormatter
Class
Using the NumberFormatter
class from the Intl
extension to format currency is an upgrade over many manual solutions.
Here’s why:
- it helps you adapt the formatting to the conventions of different locales, such as decimal points and thousand separators
- it handles various currency symbols automatically based on the currency code you specify
- it lets you avoid precision issues that might happen with the use of
floatVal()
- it has cleaner code
Here are the steps to follow so you can use the NumberFormatter
class:
- set the locale and the amount:
- create the
NumberFormatter
instance that takes in thelocale
and the kind of formatting you want, in this case, currency :
- call the
formatCurrency()
method on the instance. It takes the amount and currency code as parameters:
Here’s the full code:
And here’s another example that formats the Naira:
You can make the whole process a reusable code by creating a function that takes an amount
, currency
, and locale
as arguments:
Thank you for reading!