The PHP function number_format
() is intended for bitwise formatting of numbers with separation of the fractional part. The specific format of the received value depends on the number of arguments passed. The function can take one, two or four parameters and returns the processed value as a string.
Formatted number
The first and mandatory argument to the number_format()
function in PHP is the number itself to be formatted. The expression will look like this:
string number_format(float $number)
The $number
parameter must be a floating point number.
The result of the function will be a string containing the original number, broken by digits. The fractional part will be discarded with rounding. A comma is used as a separator.
<?php $number1 = 12345678.4321; $result1 = number_format($number1);
In the second example, the fractional part was rounded.
Fractional part
If you want to save the fractional part, you need to pass the second argument to the PHP function number_format
().
string number_format(float $number, int $decimals)
$decimals
is an integer that determines the number of decimal places to keep. By default, it is zero, so when passing one argument, the fractional part is discarded.
Having accepted two parameters, the function will return a formatted string, using a period for the separator of the integer and fractional parts.
<?php $number1 = 12345678.4321; $result1 = number_format($number1, 2);
In this case, rounding of the fractional part also occurs. Zeros are substituted for the missing digits.
Custom delimiters
The standard separators used by the PHP number_format
() function can be replaced with any other characters. The third parameter is responsible for the fractional part separator, and the fourth is for the interdigit character.
string number_format(float $number, int $decimals, string $dec_point, string $thousands_sep)
Both $dec_point
and $thousands_sep
are string data. You can pass any character as a separator, as well as a space or an empty string. Of the sequence of characters, only the first will be used, the rest will be cut off.
The php number_format function works in examples with four parameters:
<?php $number1 = 12345678.4321; $number2 = 12345678.5678; $number3 = 12345678; $result1 = number_format($number1, 5, '.', ',');
Separators are replaced by custom ones, all other rules are saved.
The PHP function number_format
() gives the programmer a lot of room to format numeric values. To get an adequate result, it is important to follow the syntax set by the specification and remember that the value returned by the function has a string type.