Dealing with currency, commas and decimals in PHP

If you are dealing with money on your code, you must know how to display comma when it reaches a thousand or million or billion and so on. You also need to handle the decimal places. Money usually have only 2 decimal places. If the money is a whole number, you still need to add 2 zeroes as decimals.

Good news! PHP has a built-in function that can do this for you. All you have to do is to call number_format

Example 1:

$number = 123456789.12345;
echo number_format($number, 2);

Output 1:

123,456,789.12

Example 2:

$number = 9876;
echo number_format($number, 2);

Output 2:

9,876.00