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:
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
- Google reCAPTCHA v3 in PHP
- Generate QR code using PHP
- Dynamic dependent select box using jQuery, Ajax, and PHP
- How to set or get default timezone in PHP
- Resize an image using the GD library in 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.
<!--?php
$num = "20000000";
echo number_format($num);<p-->
// 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
<!--?php
$num = "454656.4567";
echo number_format($num, 2);<p-->
// 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.
<!--?php
$num = "454656.4587";
echo number_format($num, 2, ',', '#');<p-->
// 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.
<!--?php
$num = "454656.4269";
echo number_format($num, 3, '.', '');<p-->
// Output: 454656.427
?>
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! ๐