What's the correct way to round a PHP string to 2 decimal places?
$number = "520"; // It's a string from a DB
$formatted_number = round_to_2dp($number);
echo $formatted_number;
The output should be 520.00
;
How should the round_to_2dp()
function definition be?
Use
round()
(use if you are expecting number in float format only, else use number_format() as answer given by Codemwnci ):From the manual:
...
You can use PHP round() function.
For conditional rounding off ie. show decimal where it's really needed otherwise whole number
123.56 => 12.56
123.00 => 123
This will display exactly two digits after decimal.
Advantage: If you want to display two digits after float value only and not for int then use this.
I make my own.
Here I getting 2 decimal after .(dot) using function..
Results from the above function:
New Correct Answer
Use the PHP native function bcdiv