
PHP provides powerful tools for formatting and handling numbers, especially when it comes to localization, currency formatting, and handling different number systems. One such tool is the NumberFormatter
class, which is part of the intl
(Internationalization) extension. This class offers robust methods for formatting numbers in a variety of ways based on locale and specific formatting rules. Let's explore this class in detail and its practical uses.
What is the NumberFormatter
Class?
The NumberFormatter
class in PHP is a part of the intl
extension and is designed to format numbers according to various patterns, locales, and types. It can be used for formatting numbers as integers, decimals, percentages, and currencies. The class also offers features for rounding and grouping numbers, making it useful for creating applications that need to support multiple languages and regions.
The NumberFormatter
class is a wrapper around the ICU (International Components for Unicode) library, which provides comprehensive localization support. This allows PHP developers to work with numbers in a way that respects cultural conventions (e.g., the use of commas or periods as thousands separators).
Enabling the intl
Extension
Before diving into the NumberFormatter
class, ensure that the intl
extension is enabled in your PHP installation. To check if it is enabled, run the following command in your terminal:
php -m | grep intl
If it's not enabled, you may need to install or enable the extension. On Ubuntu, you can install it with the following:
sudo apt install php8.4-intl
You can replace the PHP version as per your requirement.
After installation, restart your web server:
sudo service apache2 restart
Creating a NumberFormatter
Instance
To start using the NumberFormatter
class, you need to create an instance of it by specifying the locale and the desired formatting style. The constructor requires two parameters:
- Locale: A string representing the language and country in which the number should be formatted.
- Style: A constant indicating the type of number formatting.
Here’s how you can instantiate a NumberFormatter
object:
$locale = 'en_US'; // Locale: English (United States)
$style = NumberFormatter::DECIMAL; // Style: Decimal
$fmt = new NumberFormatter($locale, $style);
NumberFormatter Styles
The NumberFormatter class supports the following styles:
- DECIMAL: For general number formatting (default).
- CURRENCY: For formatting numbers as currency (e.g., $1,000.00).
- PERCENT: For formatting numbers as percentages (e.g., 50%).
- SCIENTIFIC: For scientific notation (e.g., 1.23e+4).
- SPELLOUT: For writing numbers as words (e.g., "One thousand").
- ORDINAL: For formatting numbers as ordinal numbers (e.g., "1st", "2nd").
- DURATION: For formatting durations (e.g., "1 hour, 30 minutes").
For example:
$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $fmt->format(1234.56); // Output: $1,234.56
Formatting Numbers
Once you have instantiated the NumberFormatter
, you can use the format()
method to format a number according to the specified style.
Basic Number Formatting
$fmt = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $fmt->format(1234567.89); // Output: 1,234,567.89
In this example, the number is formatted with commas as thousands separators.
Currency Formatting
$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $fmt->format(1234567.89); // Output: $1,234,567.89
The number is formatted as currency, and the locale determines the currency symbol (in this case, $
for US dollars).
Percentage Formatting
$fmt = new NumberFormatter('en_US', NumberFormatter::PERCENT);
echo $fmt->format(0.25); // Output: 25%
Here, the number is formatted as a percentage.
Customizing Number Formatting
Setting Precision
You can control the number of decimal places or significant digits using setAttribute()
. The NumberFormatter::ROUND_HALF_UP
rounding mode is often used for financial calculations.
Example:
$fmt = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo $fmt->format(123.456); // Output: 123.46
This sets the number of decimal places to 2.
Using Grouping (Thousands Separator)
You can control the use of thousands separators (grouping) with the setAttribute()
method:
$fmt = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
$fmt->setAttribute(NumberFormatter::GROUPING_USED, 1); // Enable grouping
echo $fmt->format(1234567); // Output: 1,234,567
You can disable grouping by setting GROUPING_USED
to 0
:
$fmt->setAttribute(NumberFormatter::GROUPING_USED, 0);
echo $fmt->format(1234567); // Output: 1234567
Parsing Numbers
In addition to formatting numbers, the NumberFormatter
class also allows you to parse formatted numbers back into their numeric values. This can be particularly useful when accepting user input.
You can use the parse()
method for parsing a number from a string:
$fmt = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
$number = $fmt->parse('1,234,567.89');
echo $number; // Output: 1234567.89
Parsing with Different Locales
The NumberFormatter
respects locales, so it can correctly parse numbers with different conventions (e.g., comma vs. period as a decimal separator).
$fmt = new NumberFormatter('de_DE', NumberFormatter::DECIMAL); // German locale
$number = $fmt->parse('1.234.567,89'); // German style
echo $number; // Output: 1234567.89
In this case, the German format uses periods for grouping and commas for decimal points.
Handling Errors
If there is an error in formatting or parsing, the NumberFormatter
class will set an error code. You can use getErrorCode()
to retrieve the error code and getErrorMessage()
to get a human-readable message.
$fmt = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
$fmt->parse('abc'); // Invalid number
echo $fmt->getErrorCode(); // Output: 4 (invalid data)
echo $fmt->getErrorMessage(); // Output: Invalid character
Locale-Specific Number Formatting
One of the major advantages of using the NumberFormatter
class is that it automatically handles locale-specific number formatting. For example, in France, numbers are grouped with spaces, and decimals are represented with commas.
$fmt = new NumberFormatter('fr_FR', NumberFormatter::DECIMAL); // French locale
echo $fmt->format(1234567.89); // Output: 1 234 567,89
Practical Use Cases
-
Multi-lingual Websites: When building websites that cater to multiple languages and regions, the
NumberFormatter
class ensures that numbers, currencies, and percentages are formatted according to the local conventions. -
E-commerce: For online stores, formatting prices and currencies correctly is essential. The
NumberFormatter
class allows you to format prices dynamically based on user location. -
Financial Applications: Handling precise decimal places, rounding, and currency formatting are common in financial apps. The
NumberFormatter
class simplifies these tasks. -
Internationalization: When building applications that target global audiences,
NumberFormatter
provides an easy way to format numbers based on the locale, ensuring the user experience is consistent and culturally appropriate.
Conclusion
The NumberFormatter
class in PHP is an essential tool for developers working with numbers in an international context. It provides a flexible and powerful way to format and parse numbers based on locale, style, and customization options. By leveraging this class, you can ensure that your applications respect regional conventions and deliver a user-friendly experience for people across the globe.
Categories
Laravel (6) Software tools (2) Shared Hosting (1) Validation Rule (1) Laravel Package (2) PHP (1)
Author:
Mehul Bawadia is a Full Stack Developer in Laravel and VueJs, based in Mumbai, India. He has an overall experience of 8 years in the website development field. When he is not working, you will find him learning new stuff that is not related to work.
Process Followed
1. Discover
In this process, I learn more about the requirements from you and/or from the client, and come up with varios permutations and combinations to meet the requirements.
2. Design
Once I learn properly, I do the design of the requirements that you gave keeping things aesthetically pleasing & useable for your audience.
3. Develop
Once you and/or the client is happy with the design(s), I start with the development process of the said requirements.
4. Deploy
After development, I will send the developed task to the client for reviewing. Once confirmed, will be deployed to the live server.
Tech Stack
HTML 5
CSS 3
TailwindCSS
JavaScript
PHP
MySQL
Laravel
VueJs
Spare time Projects
Few of the simple projects simply to learn.