Coding

[Solved -7 Answers] PHP – show a number to 2 decimal places

What’s the correct way to round a PHP string to 2 decimal places?

php code
$number = "520"; // It's a string from a DB

$formatted_number = round_to_2dp($number);

echo $formatted_number;

OutputĀ 

“520.00”;

How function round_to_ 2dp() definition should be?

  • You can use number_format():
php code
return number_format((float)$number, 2, '.', '');

Example:

javascript code
$foo = "105";
echo number_format((float)$foo, 2, '.', '');  // Outputs -> 105.00
  • This function returns a string.

Alternatively,

javascript code
$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00

Try:

javascript code
$number = 1234545454; 
echo  $english_format_number = number_format($number, 2);
 

javascript code
$decimals = 2;
$number = 221.12345;
$number = $number * pow(10,$decimals);
$number = intval($number);
$number = $number / pow(10,$decimals);

javascript code
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 
  • It will return 5.98 without rounding the number

php code
bcdiv($number,1,2) //2 varies for digit after decimal
  • This will display exactly two digit after decimal.

Advantage:

If you want to display two digit after float value only and not for int then use this.

  • Number without round
php code
$double = '21.188624';
echo intval($double).'.'.substr(end(explode('.',$double)),0,2);

About the author

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment

X