How to parse currency in PHP?

Amir Reza Mehrbakhsh
2 min readAug 11, 2024

--

Photo by Vladimir Solomianyi on Unsplash

I received an array of prices from the front-end and my task was to sum them up. However, the prices were in string format instead of float, so I needed to convert them before performing the calculation.

$prices = [
"$100,200.25",
"$200,000.25"
]

Initially, I thought this would be simple. I can use regex to extract the numeric values, including the decimal point, and remove any characters like dollar sign, spaces, or commas. Then, I could cast them to floats in PHP and sum them up.

Easy, right? Well, It works but only for some situations.

It turns out that number formatting varies depending on the user’s locale. For instance, the format you saw earlier is for English language, where a period is used as a decimal point and a comma as a thousand separator. However, this format is completely different in, say, the German locale, where the roles of the comma and period are reversed. Moreover, in English, the dollar sign is placed at the beginning, whereas in other locales it might appear at the end.

In this article, we’ll explore how can we handle this variation.

In fact front-end utilizes the Intl object in JavaScript. This object includes language-sensitive functions, including a NumberFormat method. You can use this method to format a floating-point number as a string, tailored to a specific locale and currency.

new Intl.NumberFormat('de', { style: 'currency', currency: 'EUR' }).format(100200.25)

This results in ‘100.200,25 €’. Note that this includes a non-breaking space ( ). If you replace it with a regular space, it won’t work correctly. That’s why it’s crucial to generate the price programmatically.

Now, let’s move on to creating a similar formatter for the German locale in PHP.

$formatter = numfmt_create('de', NumberFormatter::CURRENCY);

The locale typically comes from the `Accept-Language` HTTP header.

Now, let’s parse our currency:

$value = numfmt_parse_currency($formatter, "100.200,25 €", $currency);
// 100200.25

The third argument is a pointer and will be used to receive the currency name (a 3-letter ISO 4217 currency code like EUR).

If this method encounters an error, it will return false, so make sure to handle it properly. You can retrieve the error message with intl_get_error_message()

if ($value === false) {
throw new InvalidArgumentException(intl_get_error_message());
}

So far, we could simply convert the input into a float. Similarly, we can convert a float to its string representation:

$string = numfmt_format_currency($formmater, 100200.25, $currency);
// 100.200,25 €

--

--