3 Ways To Add Commas To A Number In PHP

Welcome to a short tutorial on how to add commas to numbers in PHP. Need to format and present a “nice-looking” number to the users?

The common ways to add commas to numbers in PHP are:

  1. Use the number_format() function. For example, $num = number_format(12345.678, 2);
  2. Use regular expressions. For example, $num = preg_replace("/\B(?=(\d{3})+(?!\d))/", ",", 12345.78);
  3. Manually split the number, add commas, and combine them back.
    • $num = explode(".", 12345.78);
    • $num[0] = implode(",", str_split(strrev($num[0]), 3));
    • $num = strrev($num[0]) . "." . $num[1];

That covers the quick basics, but read on if you need more concrete examples.

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Add Comma Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

ADD COMMAS IN PHP

All right, let us now get into the various ways and examples of adding commas to numbers in PHP.

 

METHOD 1) NUMBER FORMAT

1-number-format.php
<?php
// (A) THE NUMBER
$num = 12345.675;
 
// (B) ADD COMMAS
$formatted = number_format($num, 2);
echo $formatted; // 12,345.68
 
// (C) BLANK SPACES AS THOUSANDS SEPARATOR
$formatted = number_format($num, 3, ".", " ");
echo $formatted; // 12 345.675
 
// (D) ROUND BEFORE FORMATTING
$formatted = round($num, 2, PHP_ROUND_HALF_DOWN);
$formatted = number_format($formatted, 2);
echo $formatted; // 12,345.67

The number_format() format function is probably the easiest way to add commas to a number, and it takes in 4 parameters:

  • The first parameter is the number itself.
  • Followed by the number of decimal places.
  • The decimal separator defaults to . if omitted.
  • Lastly, the thousands separator defaults to , if omitted.

This shouldn’t be much of a mystery, but take extra note that the rounding cannot be controlled. If you have your own “special rounding rules”, you will have to do it manually before calling number_format().

 

 

METHOD 2) REGULAR EXPRESSION

2-regex.php
<?php
// (A) THE NUMBER
$num = 12345.78;
 
// (B) INSERT COMMAS
$pattern = "/\B(?=(\d{3})+(?!\d))/";
$replace = ",";
$commas = preg_replace($pattern, $replace, $num);
echo $commas; // 12,345.78

The good old regular expressions… Not going to explain too much on this one, as it is a whole can of worms. But in this example, that $pattern simply inserts a comma for every 3 digits.

 

METHOD 3) MANUAL FORMAT

3-manual.php
<?php
// (A) THE NUMBER
$num = 12345.678;
//$num = 1234567;
 
// (B) SPLIT WHOLE NUMBER & DECIMAL PLACES
$arrange = explode(".", $num);
 
// (C) ADD COMMAS
$arrange[0] = strrev($arrange[0]);
$arrange[0] = str_split($arrange[0], 3);
$arrange[0] = implode(",", $arrange[0]);
$arrange[0] = strrev($arrange[0]);
 
// (D) DEAL WITH DECIMALS
// ROUND UP OR ROUND DOWN AS YOU SEE FIT
if (isset($arrange[1])) {
  $arrange[1] = "0.$arrange[1]";
  $arrange[1] = (string)round($arrange[1], 2);
  $arrange[1] = substr($arrange[1], 2);
}
 
// (E) COMBINE BACK
$num = isset($arrange[1])
  ? "$arrange[0].$arrange[1]"
  : $arrange[0] ;
echo $num;

While number_format() is convenient, we cannot control the rounding and number of digits to add a separator. So if you want “absolute control”, a manual process is the only way to go. This is a little confusing at first, but let us go through this quickly:

  • First, we don’t want to add commas to the decimals. So we split the whole number and decimals apart – $arrange = explode(".", $num)
  • Next, we reverse the whole number. For example, 1234 to 4321$arrange[0] = strrev($arrange[0])
  • Then, add commas to the number (split into 3 digits then implode). For example, 4321 to 432,1$arrange[0] = implode(",", str_split($arrange[0], 3))
  • Reverse the number to get back the “original”. For example 432,1 to 1,234$arrange[0] = strrev($arrange[0])
  • Lastly, combine the whole numbers and decimals back – $num = "$arrange[0].$arrange[1]".

Long-winded, but this offers a lot of control – Round the number however you wish, set the number digits to add a comma, specify the separator, etc…

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Add Comma To Numbers In PHP (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *