Current Location: Home> Latest Articles> How to Format Currency Values with Decimal Points Using money_format? A Practical Guide

How to Format Currency Values with Decimal Points Using money_format? A Practical Guide

M66 2025-06-22

1. What is money_format?

money_format() is a function that formats numbers into currency strings based on the current locale setting. Its syntax is as follows:

string money_format ( string $format , float $number )

Where:

  • $format is the format control string, similar to the one used in sprintf();

  • $number is the number (amount) you wish to format.


2. Setting the Correct Locale

In order for money_format() to work correctly, you must first set the locale environment. You can use the setlocale() function to set it. For example, setting it to the US locale format:

setlocale(LC_MONETARY, 'en_US.UTF-8');

Note that different systems (especially Windows and Linux) may have different support for locales, so you may need to install the corresponding language pack.


3. Example of Formatting Currency with Decimal Points

Here is a complete example of formatting an amount:

setlocale(LC_MONETARY, 'en_US.UTF-8');
<p>$amount = 1234.56;<br>
echo money_format('%.2n', $amount);<br>

The output may be:

$1,234.56

Where:

  • '%.2n' indicates that the currency format uses two decimal places;

  • n is the currency format type defined by the locale;

  • .2 specifies the number of decimal places.


4. Multi-language Currency Display

If you want to display amounts in different formats based on the user's language, you can dynamically set the locale using setlocale():

$amount = 9876.54;
<p>setlocale(LC_MONETARY, 'de_DE.UTF-8');<br>
echo "German format: " . money_format('%.2n', $amount) . "\n";</p>
<p>setlocale(LC_MONETARY, 'fr_FR.UTF-8');<br>
echo "French format: " . money_format('%.2n', $amount) . "\n";<br>

Output:

German format: 9.876,54 €
French format: 9 876,54 €

This is especially useful for internationalized websites (such as https://m66.net/ecommerce/intl-support).


5. Alternative (for PHP 8.0 and above)

As mentioned, money_format() has been removed in PHP 8. If you are using a newer version of PHP, it is recommended to use NumberFormatter (from the intl extension) instead:

$amount = 5678.90;
<p>$fmt = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);<br>
echo $fmt->formatCurrency($amount, 'USD');<br>

Output:

$5,678.90

Using NumberFormatter not only ensures compatibility with newer versions but also offers stronger internationalization support, making it suitable for production environments.