Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
The number_format() function in PHP is used to format numbers by adding commas, decimal points, or customizing their appearance for better readability. It is commonly used to display currency values or large numbers in a structured format. This function allows specifying decimal places and separators.
In this article, we will discuss the syntax, parameters, return values, and examples of the PHP number_format() function.
Definition and Usage
The `number_format()` function in PHP is used to format numbers. It takes a number as input & returns it in a more readable form by adding separators like commas or decimals. This function is especially helpful when you need to display large numbers, currency values, or data requiring specific decimal precision.
For example, if you have a number like 1000000, it can be hard to read at first glance. Using `number_format()`, you can convert it into "1,000,000," which is much easier to understand. The function has multiple parameters that allow you to customize how the number is formatted.
Syntax
The syntax of the number_format() function is as follows:
decimals (Optional): Specifies the number of decimal points. Default is 0.
decimal_separator (Optional): The character used to separate decimals.
thousands_separator (Optional): The character used to separate thousands.
Let’s look at an example where we format a number with two decimal places & use a comma as the thousands separator:
<?php
// Original number
$number = 1234567.891;
// Format the number
$formattedNumber = number_format($number, 2, '.', ',');
// Output the result
echo $formattedNumber;
?>
You can also try this code with Online PHP Compiler
2. `number_format()` formats the number with 2 decimal places, using "." as the decimal point & "," as the thousands separator.
3. The result is stored in `$formattedNumber` & displayed using `echo`.
This function is flexible. If you don’t specify all parameters, PHP will use default values. For instance, if you only provide the number, it will add commas as thousand separators but won’t include decimals.
<?php
// Format without specifying decimals
$number = 1234567;
echo number_format($number);
?>
You can also try this code with Online PHP Compiler
The number_format() function accepts up to four parameters:
Parameter
Description
Required
Default
number
The number to format
Yes
N/A
decimals
Number of decimal places
No
0
decimal_separator
Symbol to separate decimal values
No
.
thousands_separator
Symbol to separate thousands
No
,
Return Value
The number_format() function returns a string representing the formatted number. It does not modify the original number but returns a new formatted version.
Example
Example 1: Formatting a number with default settings
The function ensures the number appears in a proper currency format with two decimal places.
Precision and Rounding
When working with numbers, precision is important. Precision refers to the number of digits after the decimal point, & rounding ensures that numbers are displayed in a way that avoids unnecessary complexity. PHP’s `number_format()` function handles both precision & rounding automatically based on the parameters you provide.
By default, if you don’t specify the number of decimal places, `number_format()` rounds the number to the nearest whole value. For example:
<?php
// Original number
$number = 1234.5678;
// Format without specifying decimals
$formattedNumber = number_format($number);
// Output the result
echo $formattedNumber;
?>
You can also try this code with Online PHP Compiler
In this case, the number is rounded to the nearest whole number (1235) because no decimal places were specified.
To control the precision, you can specify the number of decimal places as the second parameter. For example, let’s format the same number with two decimal places:
<?php
// Original number
$number = 1234.5678;
// Format with two decimal places
$formattedNumber = number_format($number, 2, '.', ',');
// Output the result
echo $formattedNumber;
?>
You can also try this code with Online PHP Compiler
Here, the number is rounded to two decimal places (1234.57). Notice how PHP automatically rounds up from 1234.5678 to 1234.57.
Rounding behavior follows standard mathematical rules:
- If the digit after the last decimal place is 5 or higher, the number rounds up.
- If it’s less than 5, the number rounds down.
Let’s see another example where we format a number with three decimal places:
<?php
// Original number
$number = 987.654321;
// Format with three decimal places
$formattedNumber = number_format($number, 3, '.', ',');
// Output the result
echo $formattedNumber;
?>
You can also try this code with Online PHP Compiler
In this case, the number is rounded to three decimal places (987.654). The fourth decimal digit (3) causes the number to round down.
You can also use custom decimal points & thousand separators while controlling precision. For example, some countries use a comma as the decimal separator instead of a period. For example:
<?php
// Original number
$number = 5000.1234;
// Format with a comma as the decimal separator
$formattedNumber = number_format($number, 2, ',', '.');
// Output the result
echo $formattedNumber;
?>
You can also try this code with Online PHP Compiler
The `number_format()` function is widely used in real-world applications to make numbers more readable & professional. Let’s discuss some of the common scenarios where this function is helpful, with the help of practical examples for each case.
1. Displaying Currency Values
When working with financial data, formatting numbers as currency is essential. For example, displaying prices or salaries requires proper decimal precision & thousand separators. Let’s see how you can format a number to represent currency:
<?php
// Original price
$price = 1999.99;
// Format the price with two decimal places & a dollar sign
$formattedPrice = '$' . number_format($price, 2, '.', ',');
// Output the result
echo $formattedPrice;
?>
You can also try this code with Online PHP Compiler
In this example, the number is formatted with two decimal places, & a dollar sign is added manually before the formatted number. This approach works well for e-commerce websites or financial apps.
2. Formatting Large Numbers for Reports
When dealing with large datasets, such as population counts or sales figures, adding thousand separators improves readability. Let’s discuss an example of formatting a large number:
<?php
// Population count
$population = 789456123;
// Format the number with commas as thousand separators
$formattedPopulation = number_format($population);
// Output the result
echo $formattedPopulation;
?>
You can also try this code with Online PHP Compiler
This makes it easier to understand the magnitude of the number at a glance.
3. Adapting to Regional Standards
Different regions use different formats for numbers. For instance, some countries use a comma as the decimal separator instead of a period. You can customize `number_format()` to match these standards. For example:
<?php
// Original number
$distance = 1500.75;
// Format the number with a comma as the decimal separator
$formattedDistance = number_format($distance, 2, ',', '.');
// Output the result
echo $formattedDistance;
?>
You can also try this code with Online PHP Compiler
This format is commonly used in European countries, making your application adaptable to global audiences.
4. Displaying Percentages
Percentages often require one or two decimal places for clarity. Let’s see how you can format a percentage value:
<?php
// Original percentage
$percentage = 0.8567;
// Multiply by 100 & format with one decimal place
$formattedPercentage = number_format($percentage 100, 1, '.', '') . '%';
// Output the result
echo $formattedPercentage;
?>
You can also try this code with Online PHP Compiler
In this example, the number is multiplied by 100 to convert it into a percentage, formatted with one decimal place, & a percentage sign is appended.
5. Handling Scientific Data
Scientific data often involves very large or small numbers. While PHP doesn’t directly support scientific notation in `number_format()`, you can still format such numbers for better readability. For example:
<?php
// Distance in kilometers
$distance = 149597870; // Average distance from Earth to Sun
// Format the number with commas
$formattedDistance = number_format($distance);
// Output the result
echo $formattedDistance;
?>
You can also try this code with Online PHP Compiler
This makes scientific data more accessible to non-experts.
Frequently Asked Questions
What happens if I do not specify any optional parameters?
If you only provide a number, number_format() rounds it to the nearest integer and separates thousands using a comma.
Can I use number_format() for negative numbers?
Yes, number_format() works with negative numbers, preserving the negative sign.
Is number_format() useful for calculations?
No, number_format() returns a string, so it should only be used for display purposes, not calculations.
Conclusion
In this article, we learned about the PHP number_format() function and how it helps format numbers with decimal points and thousand separators. We also explored different ways to generate random numbers in PHP using functions like rand(), mt_rand(), and random_int(). Understanding these functions makes it easier to handle numeric data efficiently in PHP applications.