PHP 2 decimal places without rounding code example

In this article, I show you how to get Php 2 decimal places without rounding off the actual number. This is important when you are working on some math calculation script and your results are varying because of the decimal values. This is a very common scenario to handle decimal places in numeric figures.

 

PHP 2 decimal places without rounding

 

Suppose you have below value  –

30.67798

And you want the get value up to two decimal without rounding off using PHP and below is the expected output –

30.67

Example -1

$amount = 30. 67798;
$rounded_amount = round($amount, 2);

Output –

30.67

Here I used the round method to round the decimal value up to two places. The first parameter is the actual value and the second parameter is the precision. The precision parameter is optional and the default value is Zero.

$rounded_amount = round($amount, 0);

Output –

  1. 67798

Example -2

PHP 2 decimal places without rounding

Let’s understand the round() method in PHP. It round the decimal point value.

Note –

  1. To round a number up to the nearest integer, look at the ceil().

Example 1

<?php
echo(ceil(0.70));
echo(ceil(2.60))
?>

Output

1
3

 

  1. And to round down to the nearest integer, use the floor method of PHP.
<?php
echo(floor(0.70) . "<br>");
echo(floor(2.40));
?>

Output

0
2

 

Round to 2 decimal places PHP

Now let’s take one more example to round to two decimal places in PHP.

<!DOCTYPE html>
<html>
<body>
<?php

echo roundoffvalue(2.750,2);
function roundoffvalue($number, $afterDot = 2){
$num1 = $number * pow(10, $afterDot);
$num2 = floor($a);
$num3 = pow(10, $afterDot);
echo "num1 = $num1, num2 = $num2, num3= $num3<br/>";
return round($number,$afterDot) ;
}
?>
</body>
</html>

Output –

num1 = 275, num2 = 0, num3= 100
2.75

Example 3-

Have a look at the below expression so that you will never forget how to round to two decimal places in PHP.

<?php

echo(round(10.0335) . "<br>");
echo(round(40.5666) . "<br>");
echo(round(302.409) . "<br>");
echo(round(-10.305) . "<br>");
echo(round(60.12345));

?>

Output –

10
41
302
-10
60

Note – The round method expects only the number value if you pass any string the syntax error has occurred.

 

Conclusion

How is how you can use the PHP round method to round to two decimal places in PHP.

Posted in PHP