PHP NumberFormatter with Examples — Phpflow.com

Parvez Alam
2 min readOct 22, 2022

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: The 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: Output:

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

Originally published at https://www.phpflow.com on October 22, 2022.

--

--

Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge. https://www.phpflow.com/