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?
Try:
The output will be:
Use PHP number_format() function.
You can use number_format():
Example:
This function returns a string.
Alternatively,
You can use php
printf
orsprintf
functions:example with
sprintf
:You can run same without
echo
as well,ex: sprintf("%.3f",$num);
output:
Alternatively, with
printf
:output:
If you want to use 2 decimal digit in your entire project you can define
Then the following function will produce your desired result
But if you don't use bcscale function you need to write the code as follow to get your desire result
To know more
http://php.net/manual/en/ref.bc.php
http://php.net/manual/en/function.bcscale.php