Create custom money format function in php with allow two digit only
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:
php.net/manual/en/function.number-format.php
And you can find more information about the preg_replace()
function at the following link: