money_format is a built-in formatting function in PHP, which is used to format currency strings according to locale. Its syntax is as follows:
<code> string money_format ( string $format , float $number ) </code>$format is a format string that defines the output format.
$number is the number that needs to be formatted.
It should be noted that the money_format function depends on the system's locale. If locale is not set correctly, the currency symbol or format may not be displayed correctly.
Before calling money_format , you need to use the setlocale function to set the appropriate area environment. For example, set to the United States English environment:
<code> setlocale(LC_MONETARY, 'en_US.UTF-8'); </code>If your system does not support this locale, it needs to be adjusted according to the server environment.
The format string of money_format starts with % and can have multiple modifiers after it:
%i : International currency format (including currency code, such as USD)
%n : Local currency format (including currency symbols)
Suppose we have an amount of 1234.5 and want to use money_format to output the format with dollar signs, millites, and retain the two decimals.
<code> <?php // Set the regional environment to American English setlocale(LC_MONETARY, 'en_US.UTF-8');$amount = 1234.5;
// Use %n format to output local currency format, retain two decimal places by default
$formatted = money_format('%n', $amount);
echo $formatted;
?>
</code>
The output result is usually:
<code> $1,234.50 </code>The money_format function is only valid on Linux/Unix systems, and is not supported in Windows environment.
After PHP 7.4, it is officially recommended to use the NumberFormatter class instead of money_format because the latter has been marked as abandoned.
If you need to use cross-platform and compatible with new PHP versions, it is recommended to use NumberFormatter .
Implement the same functionality using NumberFormatter :
<code> <?php $amount = 1234.5; $formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY); echo $formatCurrency($amount, 'USD'); ?> </code>The output is the same:
<code> $1,234.50 </code>Although money_format is still used in many old projects, it is recommended to use the NumberFormatter class to format the currency for compatibility and future maintenance considerations. This article demonstrates how to use money_format output to retain the standard currency format of two decimal places, and provides a modern alternative that allows developers to make flexible choices based on their needs.