PHP NumberFormatter with Examples

This tutorial help to format a number using numberformatter. We’ll format a Number to a Dollar Amount in PHP Using the NumberFormatter::formatCurrency Function.

I’ll convert a number in currency format using number_format(the old way) as well as the latest way using NumberFormatter.

NumberFormatter

This is the latest and arguably the easiest method to format numbers to strings showing different currencies. Please make sure the extension=intl is enabled in php.ini.

Syntax:

string numfmt_format_currency ( NumberFormatter $fmt , float $Amount , string $currency )

There are three parameters:

  • Formatter: This is the NumberFormatter object.
  • Amount: which is the numeric currency value.
  • Currency: ISO 4217 dictates the currency to use.

It returns a String representing the formatted currency value.

Example:

Let’s take an example, If the number is 9988776.65 the results will be:

9 988 776,65 € in France
9.988.776,65 € in Germany
$9,988,776.65 in the United States

Option 1: NUMBER FORMAT

The number format is a very common method to format a number using PHP.

Syntax:

number_format(amount, decimals, decimal_separator, thousands_separator).

  • amount: The number being formatted.
  • decimals: Sets the number of decimal digits. If 0, the decimal_separator is omitted from the return value.
  • decimal_separator: Sets the separator for the decimal point.
  • thousands_separator: Sets the thousands separator.

The sample code to convert a number in currency format:

<?php
$amount = 4533.44;
$usd = "$" . number_format($amount, 2, ".", ",");
echo $usd;
?>

Output:

$4,533.44

Option 2: NUMBER FORMATTER

This is the easiest way to format a number in PHP 7, but make sure that extension=intl is enabled in php.ini.

<?php
$amount = 4533.44;

$nf = new NumberFormatter("en_US", NumberFormatter::CURRENCY);
$usd = $nf->formatCurrency($amount, "USD");
echo $usd;

Output:

$4,533.44

REFERENCES

Leave a Reply

Your email address will not be published. Required fields are marked *