The number_format() function is an inbuilt function in PHP which is used to format a number with grouped thousands. It returns the formatted number on success otherwise it gives E_WARNING on failure.
Syntax:
string number_format ( $number, $decimals, $decimalpoint, $sep )
Parameters: This function accepts four parameters as mentioned above and described below:
- $number: It is required parameter which specified the number to be formatted. If no other parameters are set, the number will be formatted without decimals and with the comma (, ) as the thousands separator.
- $decimals: It is optional parameter and used to specifies decimals. If this parameter is set, the number will be formatted with a dot (.) as the decimal point.
- $decimalpoint: It is optional parameter and used to specifies the string to use for the decimal point.
- $sep: It is optional parameter and used to specifies string to use for thousands separator. If this parameter is given, then all other parameters are required.
Return Value: It returns Formatted Number in case success, otherwise it gives E_WARNING in failure.
Examples:
Input: $number = 100000
Output: 10, 000
Input: $number = 10000
$decimals = 3
$decimalpoints = "." $sep =,
Output: 10, 0000.000
Below programs illustrate The number_format() function in PHP:
Program 1:
<?php
$num1 = "999999.49" ;
echo number_format( $num1 ). "\n" ;
echo number_format( $num1 , 3). "\n" ;
$num2 = "9999999.99" ;
echo number_format( $num2 ). "\n" ;
echo number_format( $num2 , 3). "\n" ;
echo number_format( "1000000.99" , 3, "#" , "GGG" );
?>
|
Output:
999,999
999,999.490
10,000,000
9,999,999.990
1GGG000GGG000#990
Program 2: If pass anything instead of numbers it gives warning.
<?php
$num = "GFG" ;
echo number_format( $num ). "\n\n" ;
echo number_format( $num , 3);
?>
|
Output:
PHP Warning: number_format() expects parameter 1 to be float,
string given in /home/ac476aaecea758334cb8ed146bcbb8f6.php on line 5
PHP Warning: number_format() expects parameter 1 to be float,
string given in /home/ac476aaecea758334cb8ed146bcbb8f6.php on line 8
Program 3: This function does not accept three parameters, only accept 1, 2 or 4 parameters.
<?php
$num = 1000000;
echo number_format( $num , 3, ", " );
?>
|
Output:
PHP Warning: Wrong parameter count for number_format()
in /home/e426108b066d9a86366249bf7b626d19.php on line 6
Reference: http://php.net/manual/en/function.number-format.php