Home >Backend Development >PHP Tutorial >How to Format a Number to Two Decimal Places in PHP?
How to Display a Number with Two Decimal Places in PHP
In PHP, displaying a number with two decimal places can be achieved using the appropriate formatting functions.
To round a string representing a number to two decimal places, consider the following code snippet:
$number = "520"; // Assumed to be a string from a database $formatted_number = round_to_2dp($number); echo $formatted_number;
The objective is to define the round_to_2dp() function to perform the necessary rounding.
Function Definition for round_to_2dp():
One approach to achieve this is by employing the number_format() function:
function round_to_2dp($number) { return number_format((float)$number, 2, '.', ''); }
In this implementation:
number_format is utilized with the following parameters:
The above is the detailed content of How to Format a Number to Two Decimal Places in PHP?. For more information, please follow other related articles on the PHP Chinese website!