Coding

PHP: how to add a thousands separator

posted on by - 621 views

Coding could be stressful, especially when we struggle to find ways to do apparently simple things. When I started being a web developer, sometime in the 10’s, I remember working on an ecommerce website made from scratch.

That was quite a challenge, won’t deny it – and I specifically remember having troubles with prices. Since it was a real estate website, houses had really high prices, and they were just… ugly. Just imagine going through a web page and seeing all those €750000 and €1250000 and €2450000, so many numbers that you need to focus for a second to understand if that’s a million or just 125 thousands, or even twelve millions.

So, I needed a way to add a thousands separator in PHP. Eventually I found it, and it was quite simple: the only thing needed was a specific PHP function, which is…

Using number_format() to add the thousands separator

Yes, that one. number_format() is what we need to make things easy.

Now, let’s say we have a very high number, something like five millions and something.

$price = "5325297";

Right? Okay: it’s ugly, as expected. Let’s see how to make it prettier.

$price = number_format( $price, 2, '.', ',' );

Here we go: now if we echo $price, the output of what we just did should be 5,325,297.00. What we did will also add the decimal separator, which in this case is a dot – while thousands are delimited by a comma. If we want to invert things, well, it’s easy as well:

$price = number_format( $price, 2, ',', '.' );

Now the thousands are delimited by dots, and decimals by a comma.
If we’re 100% sure we will only have round numbers, we can also remove the decimals. The only thing to do here is making that 2 become 0.

$price = number_format( $price, 0, ',', '.' );

That’s it. We just made prices really pretty just by using a PHP function.
You buyers will be so happy now. Maybe.