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:
Output
3.14round() 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()functionTo 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_formatfunction to format a number to 2 decimal places:$number = 3.14159; // Use the number_format function to format the number $formatted = number_format($number, 2, '.', ''); // Output the formatted number echo $formatted; // 3.14Output
3.14We 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:
Output
3.14sprintf() 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
floatvalandnumber_formatfunctionTo format a number to 2 decimal places in PHP, you can also use the
number_format()function in combination with thefloatval()function.You can first convert the number to a string using the
floatval()function, and then use thenumber_format()function to format the string to 2 decimal places.Here is an example of how to use the
floatval()andnumber_format()functions to format a number to 2 decimal places:Output
3.14That's all about how to format number to 2 decimal places in PHP.