Formatting number using the number_format() function in PHP
Today, we’ll show you how to format the number using the number_format() in PHP.
The number_format()
is a PHP built-in function which is used to format the number of data. It returns the formatted value based on the parameter passed in function.
Syntax:
1 | number_format(num, decimals, decimalPoint, separator) |
Parameters:
- num (Required): It specifies the number to be formatted.
- decimals (Optional): It specifies how many decimals.
- decimalPoint (Optional): It specifies the string to use for the decimal point.
- separator (Optional): It specifies the string to use for a thousand separators.
Checkout more articles on PHP
Different use of number_format() function
1. Basic number format
First we use the number_format()
function with one argument to format a number with the default thousand separator. Run the following PHP script.
1 2 3 4 5 6 7 8 9 10 11 | <?php $num = "20000000"; echo number_format($num); // Output: 20,000,000 $num1 = "125467.56897"; echo number_format($num1); // Output: 125,468 ?> |
2. Decimal number format
Now, we use the number_format()
function with two arguments with the default thousand separator and decimal value
1 2 3 4 5 6 | <?php $num = "454656.4567"; echo number_format($num, 2); // Output: 454,656.46 ?> |
3. Using separator
At last we check passing all parameters in the number_format()
function. In the following example ,
is used for the decimal point and #
is used for a thousand separators.
1 2 3 4 5 6 | <?php $num = "454656.4587"; echo number_format($num, 2, ',', '#'); // Output: 454#656,46 ?> |
If you want to remove the comma (,
) from the number using the number_format()
function, you can use the following format.
1 2 3 4 5 6 | <?php $num = "454656.4269"; echo number_format($num, 3, '.', ''); // Output: 454656.427 ?> |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂