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_format(float $number, int $decimals = 0, string $dec_point = '.', string $thousands_sep = ','): string
  • $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

<?php echo number_format(1234567.891); ?>

Output:

1,234,568

Explanation: This formats the number 1234567.891 to 1,234,568, rounding to the nearest integer by default.

Example 2: Specifying Decimal Places

<?php echo number_format(1234567.891, 2); ?>

Output:

1,234,567.89

Explanation: Here, the number is formatted to two decimal places, resulting in 1,234,567.89.

Example 3: Custom Decimal and Thousands Separators

<?php echo number_format(1234567.891, 2, '.', ' '); ?>

Output:

1 234 567.89

Explanation: In this case, the thousands separator is a space (' '), and the decimal point remains '.'.

Example 4: Formatting a Large Number

<?php echo number_format(9876543210); ?>

Output:

9,876,543,210

Explanation: This formats the large number 9876543210 with thousands separators.

Example 5: Rounding and Formatting

<?php echo number_format(1234.5678, 3); ?>

Output:

1,234.568

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:

<?php echo number_format(-1234.5678, 2); ?>

Output:

-1,234.57

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.