PHP number_format() Function
The number_format() function in PHP formats a number with grouped thousands. This function accepts one, two, or four parameters (not three):
Syntax
1 2 3 |
number_format ( float $number [, int $decimals ] ) |
or
1 2 3 |
number_format ( float $number , int $decimals , string $dec_point, string$thousands_sep ) |
Parameter
number(required)- This parameter represents the number to be formatted. If no parameters are set, the number will be formatted without decimals and with comma (,) as the thousands separator.
decimals(optional)- This parameter specifies how many decimals. If this parameter is set, the number will be formatted with a dot (.) as decimal point.
decimalpoint(optional)- This parameter specifies what string to use for decimal point.
separator (optional)- This parameter specifies what string to use for thousands separator. Only the first character of separator is used.
Returns
This function returns a formatted version of number.
Example 1
1 2 3 4 5 6 7 8 9 10 |
<?php // formating a number with grouped thousands. echo number_format("2000000")."\n"; // formats a number with grouped thousands with 2. echo number_format("2000000",2)."\n"; // the number will be formatted with a dot (.) as decimal point. echo number_format("2000000",2,",","."); ?> |
Output
1 2 3 4 5 |
2,000,000 2,000,000.00 2.000.000,00 |
Example 2
1 2 3 4 5 6 7 8 9 10 |
<?php // initializing the number $number=8919.9; // printing the number echo "Your number:".$number; //formats a number with grouped thousands. echo "\n"."After using 'number_format()' function :\nFormatted number: ".number_format($number); ?> |
Output
1 2 3 4 5 |
Your number:8919.9 After using 'number_format()' function : Formatted number: 8,920 |
Example 3
1 2 3 4 5 6 7 8 |
<?php //initializing the number $n=100000000; echo "The number:".$n; echo "\n"."The formated number :".number_format($n,4); // will pass 4 zeros after the decimal point ?> |
Output
1 2 3 4 |
The number:100000000 The formated number :100,000,000.0000 |
Example 4
1 2 3 4 5 6 7 8 9 |
<?php //initializing the number $n=100000000; echo "The number:".$n; // will return 100#000#000.0000 echo "\n"."The formated number :".number_format($n,4,".","#"); ?> |
Output
1 2 3 4 |
The number:100000000 The formated number :100#000#000.0000 |