Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Show a number to two decimal places

What's the right method to round a PHP string to two decimal points?

$number = "520"; // It's a string from a database

$formatted_number = round_to_2dp($number);

echo $formatted_number;

The output ought to be 520.00;

How might the round_to_2dp() function definition be?
by

2 Answers

akshay1995
You can use number_format():

return number_format((float)$number, 2, '.', '');

Example:

$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
sandhya6gczb
Use round() (use if you are expecting a number in float format only, else use number_format()

echo round(520.34345, 2); // 520.34
echo round(520.3, 2); // 520.3
echo round(520, 2); // 520

Login / Signup to Answer the Question.