Home >Backend Development >PHP Tutorial >How to Round a PHP String to Two Decimal Places?
Rounding a Number to Two Decimal Places in PHP
In this snippet, we aim to round a PHP string to two decimal places to format it properly for output. To achieve this, we could utilize a custom function named round_to_2dp().
The function definition should be as follows, employing the number_format() function:
function round_to_2dp($number) { return number_format((float)$number, 2, '.', ''); }
Here's an example of its usage:
$number = "520"; // It's a string from a database $formatted_number = round_to_2dp($number); echo $formatted_number; // Outputs 520.00
The number_format() function takes three arguments:
In this case, we set the decimals argument to 2, specifying two decimal places. The final result is returned as a string.
The above is the detailed content of How to Round a PHP String to Two Decimal Places?. For more information, please follow other related articles on the PHP Chinese website!