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

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.



To the spot!! Thanks a lot!


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


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


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()


See i have to take the summed up value and then round it up, but round function not giving desired value.
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


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 .

We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2021 All rights reserved worldwide Privacy Policy Disclaimer