Rounding off variable values in PHP

We can round off variable values to a whole number or to some value with precision. You can read the article on number formatting to know how to format numbers using PHP. For simple rounding here is the code to do all that. WE will store the value in a variable and then display by rounding off it by using round function.

Sample code for rounding data below

$number=25.66745;
echo "The number = ". $number // will display 25.66745 
echo "<br>Rounded value of the number = ".round($number,2); // will display25.67 
echo "<br>Rounded value of the number = ".round($number); // will display 26 

Some time we may use php number formatting function to display a proper formatted number.

We can round off the number to lower value is by using floor function and we can also round off to next higher number by using ceil function in PHP

Here is a comparison between ceil(), floor() and round() function. For different input numbers we will get different values by using these functions.
ValueFloor()ceil()round()
3.7344
3.4343
3.5344
3.48343
3.62344
2222
-8.7-9-8-9
-9.5-10-9-10
-9.3-10-9-9
-9.49-10-9-9
-9.61-10-9-10
-9-9-9-9
Visitors Rating
Your Rating





Sabby

17-05-2012

To the spot!! Thanks a lot!
krish

07-11-2013

if we use 11/3 answer is 3.67 but after we use addition 3.67+3.67+3.67 answer is 11.01
this is not a correct answer how to get right value please help me
smo

07-11-2013

When we round up the value we miss further fractions so we can't expect to get back the same value after adding them. Increase the decimal value to 4 digits and then see the result.
Johan H

03-02-2014

There is more round(), you can also force it to round down using floor() or round up (even if it's 10.0001 it'd round to 11) with ceil()
suchitra

09-11-2015

See i have to take the summed up value and then round it up, but round function not giving desired value.
$b=175+0+175+0+175+175+175+175+175+468.7
+0+175+468.7+468.7+468.7+689.8+175+0+175
+175+0+175+0+0+0+468.7+468.7+689.8+4
68.7+175+175;
echo"<br>".$b;
echo "<br>".round($b);

total = 7110.5
after rounding up it gives 7110 which is not desired value. We cannot use ceil function as every time it will give the higher value i.e 7.3=8
smo1234

10-04-2016

You can round each value and then sum or use number format and then add each value with decimal. The final value you can round off to check it matches your requirement or not.

Post your comments , suggestion , error , requirements etc here .




HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer