PHP number_format() function
The number_format()
function in PHP is used to format a number with grouped thousands and specified decimal places. This function is particularly useful for displaying numbers in a more readable format, especially for financial data, where you want to present figures clearly.
Syntax:
- $number: The number to be formatted.
- $decimals: (optional) The number of decimal points to display. Default is
0
. - $dec_point: (optional) The character to use as the decimal point. Default is
'.'
. - $thousands_sep: (optional) The character to use as the thousands separator. Default is
','
. - Return Value: Returns the formatted number as a string.
Example 1: Basic Number Formatting
Output:
Explanation: This formats the number 1234567.891
to 1,234,568
, rounding to the nearest integer by default.
Example 2: Specifying Decimal Places
Output:
Explanation: Here, the number is formatted to two decimal places, resulting in 1,234,567.89
.
Example 3: Custom Decimal and Thousands Separators
Output:
Explanation: In this case, the thousands separator is a space (' '
), and the decimal point remains '.'
.
Example 4: Formatting a Large Number
Output:
Explanation: This formats the large number 9876543210
with thousands separators.
Example 5: Rounding and Formatting
Output:
Explanation: The number 1234.5678
is rounded to three decimal places, resulting in 1,234.568
.
Key Points:
- The
number_format()
function is particularly useful for formatting currency, percentages, or any other numerical data for better readability. - It can handle negative numbers and will format them appropriately.
- It returns a string, so if you need to perform further mathematical operations, you should convert it back to a number.
Example of Negative Number Formatting:
Output:
Explanation: This formats the negative number -1234.5678
to -1,234.57
, rounding to two decimal places.
In summary, number_format()
is a versatile function in PHP for formatting numbers in a way that enhances clarity and presentation, especially when dealing with large figures or financial data.