Create custom money format function in php with allow two digit only

Mandeep SinghMandeep Singh
1 min read

Here is an example of a function in PHP that you can use to format a monetary value with two decimal places:

function format_money($value) {
  // Use number_format() to add commas as thousands separators and round to two decimal places
  $formatted = number_format($value, 2);

  // Use preg_replace() to remove any extra decimal places beyond the two that were added by number_format()
  $formatted = preg_replace('/\.00$/', '', $formatted);

  // Return the formatted value
  return $formatted;
}

You can use this function by calling it with a monetary value as an argument, like this:

$value = 123456.789;
echo format_money($value); // Outputs: 123,456.79

The function first uses the number_format() function to add commas as thousands separators and round the value to two decimal places. It then uses the preg_replace() function to remove any extra decimal places beyond the two that were added by number_format(). Finally, it returns the formatted value.

You can find more information about the number_format() function at the following link:

https://www.php.net/manual/en/function.number-format.php

And you can find more information about the preg_replace() function at the following link:

https://www.php.net/manual/en/function.preg-replace.php

0
Subscribe to my newsletter

Read articles from Mandeep Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mandeep Singh
Mandeep Singh

I am Mandeep Singh, a full-stack developer. I created this Blog to bestow my coding experience and love to write on JavaScript, Next.js, Laravel and little bit Unity Game development.