How to round up a number to nearest 10?


Question

How can we round off a number to the nearest 10 in php?

Say I have 23, what code would I use to round it off to 30?

1
83
4/9/2014 7:50:17 AM

Accepted Answer

floor() will go down.

ceil() will go up.

round() will go to nearest by default.

Divide by 10, do the ceil, then multiply by 10 to reduce the significant digits.

$number = ceil($input / 10) * 10;

Edit: I've been doing it this way for so long.. but TallGreenTree's answer is cleaner.

184
5/25/2012 6:10:30 AM

round($number, -1);

This will round $number to the nearest 10. You can also pass a third variable if necessary to change the rounding mode.

More info here: http://php.net/manual/en/function.round.php


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon