Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to round a number to two decimal places

Short answer

The second argument of round() sets the number of decimal places:

<?php
 
echo round(3.14159, 2);

Output:

3.14

Always two digits

round() returns a number, so trailing zeros are not printed. To always show two digits, use number_format():

<?php
 
echo round(2.5, 2), "\n";
echo number_format(2.5, 2);

Output:

2.5
2.50

Down or up

To round in a chosen direction, multiply by 100, apply floor() or ceil() and divide back:

<?php
 
echo floor(3.789 * 100) / 100, "\n";
echo ceil(3.781 * 100) / 100;

Output:

3.78
3.79

Functions used in this recipe

  • round — Rounds a number to a given number of digits.
  • floor — Rounds a number down to the nearest integer.

Thanks for reading!

Donate to the site — we work hard for you.