Table of Contents
Using the round() function
To format a number to 2 decimal places in PHP, you can use the round() function and pass the number and 2 as arguments to the round() function.
Here is an example of how to use the round() function to format a number to 2 decimal places:
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $number = 3.14159; // Use the round function to format the number $formatted = round($number, 2); // Output the formatted number echo $formatted; |
Output
|
1 2 3 |
3.14 |
round() function accepts a number and the number of decimal places to round to as arguments, and it returns the rounded number as a float.
Using the number_format() function
To format a number to 2 decimal places in PHP, you can use the number_format() function. number_format() formats number with specified decimal places.
Here is an example of how to use the number_format function to format a number to 2 decimal places:
|
1 2 3 4 5 6 7 8 9 |
$number = 3.14159; // Use the number_format function to format the number $formatted = number_format($number, 2, '.', ''); // Output the formatted number echo $formatted; // 3.14 |
Output
|
1 2 3 |
3.14 |
We used number_format() to format number to 2 decimal places in PHP.
number_format() function accepts 4 arguments:
- the number to format,
- the number of decimal places to include, and
- the decimal point character to use.
- thousand separator which is not applicable here.
Use sprintf() function
To format a number to 2 decimal places in PHP, you can also use the sprintf() function and use the format string "%0.2f".
Here is an example of how to use the sprintf function to format a number to 2 decimal places:
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $number = 3.14159; // Use the sprintf function to format the number $formatted = sprintf("%0.2f", $number); // Output the formatted number echo $formatted; |
Output
|
1 2 3 |
3.14 |
sprintf() function accepts a format string as its first argument, and it formats the numbers that are passed as subsequent arguments according to the specified format.
Use the floatval and number_format function
To format a number to 2 decimal places in PHP, you can also use the number_format() function in combination with the floatval() function.
You can first convert the number to a string using the floatval() function, and then use the number_format() function to format the string to 2 decimal places.
Here is an example of how to use the floatval() and number_format() functions to format a number to 2 decimal places:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $number = 3.14159; // Convert the number to a string using the floatval function $string = floatval($number); // Use the number_format function to format the string $formatted = number_format($string, 2, '.', ''); // Output the formatted number echo $formatted; |
Output
|
1 2 3 |
3.14 |
That’s all about how to format number to 2 decimal places in PHP.