116 of 410 menu

The number_format Function

The number_format function allows you to format a number. It is mainly used to separate thousands with spaces, for example, it can turn 1234567 into 1 234 567.

Additionally, the function allows you to control the number of digits after the decimal point. This number is set by the second optional parameter.

For example, you can turn the fraction 12345.6789 into 12 345.68 - the function will add spaces between thousands and round the fraction to two decimal places.

The third optional parameter sets the decimal separator (by default a dot, but it can be changed). The fourth parameter must always be used together with the third one - it sets the thousands separator (by default a comma, but it can be changed, for example, to a space). That is, by default the function separates thousands with commas: turns 1234567 into 1,234,567.

Syntax

number_format(float $num, int $decimals = 0, ?string $decimal_separator = ".", ?string $thousands_separator = ","): string
number_format(number, number_of_decimals);
number_format(number, number_of_decimals, decimal_separator, thousands_separator);

Example

Let's separate thousands with a comma:

<?php echo number_format(1234567); ?>

Code execution result:

'1,234,567'

Example

Let's separate thousands with a comma, and round the fractional part to two decimal places:

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

Code execution result:

'1,234.57'

Example

Let's separate thousands with a space, round the fractional part to two decimal places, and use a slash as the decimal separator:

<?php echo number_format(1234.567, 2, '/', ' '); ?>

Code execution result:

1 234/57

Example

Let's separate thousands with a space, round the fractional part to two decimal places, and use a dot as the decimal separator:

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

Code execution result:

1 234.57

See Also

  • the printf function,
    which formats a string
byenru