Format Number With Two Decimal Places and Comma Using PHP

This tutorial will help you on how to display the number in price format using php. The feature of this tutorial is it allow you to display the number with two decimal point and put comma when the number of digits is four. To understand this tutorial follow the steps bellow.

Step 1 : Creating our function script that convert the number in price format

Copy the code bellow and save it as “index.php”.
  1. <?php
  2. function formatMoney($number, $fractional=false) {
  3. if ($fractional) {
  4. $number = sprintf('%.2f', $number);
  5. }
  6. while (true) {
  7. $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
  8. if ($replaced != $number) {
  9. $number = $replaced;
  10. } else {
  11. break;
  12. }
  13. }
  14. return $number;
  15. }
  16. ?>
  17. </php
  18.  
  19. <h2>Step: 2 Displaying our number in price</h2>
  20. The code bellow will give us the formatted number. Copy and paste it under our function code in “index.php”.
  21.  
  22. <php>
  23. <?php
  24. $tobeformated=1000000;
  25. echo formatMoney($tobeformated, true);
  26. ?>

Summary

The code bellow will display the summary of step 1 and step 2.
  1. <?php
  2. function formatMoney($number, $fractional=false) {
  3. if ($fractional) {
  4. $number = sprintf('%.2f', $number);
  5. }
  6. while (true) {
  7. $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
  8. if ($replaced != $number) {
  9. $number = $replaced;
  10. } else {
  11. break;
  12. }
  13. }
  14. return $number;
  15. }
  16. $tobeformated=1000000;
  17. echo formatMoney($tobeformated, true);
  18. ?>

Add new comment