What's the correct way to round a PHP string to two decimal places?
$number = "520"; // It's a string from a database $formatted_number = round_to_2dp($number); echo $formatted_number;
The output should be 520.00
;
How should the round_to_2dp()
function definition be?
Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.
On the Formulas tab, under Function, click Formula Builder. In number, type the number you are rounding up. In num_digits, type 0 to round the number up to the nearest whole number. In number, type the number you are rounding down.
Click the Table Tools' Layout tab, select Data and then click Formula. Click the Number Format menu and select 0.00 for two decimals.
You can use number_format():
return number_format((float)$number, 2, '.', '');
Example:
$foo = "105"; echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
This function returns a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With