Sometimes it is necessary to round a number to the nearest X (.1,5,10, etc). Below is some code to do that:
PHP ∞
1
2
3
4
5
6
7
8
9
10
11
12
|
# Round int to nearest $round_to
function round_int($n, $round_to=10){
return round($n / $round_to) * $round_to;
}
# Round float to nearest $round_to, configurable rounding down
function round_float($n, $round_to = .1, $round_down = false) {
if($round_down)
return floor(($n + $round_to / 2) / $round_to) * $round_to;
else
return ceil(($n + $round_to / 2) / $round_to) * $round_to;
}
|
Python ∞
1
2
3
|
# Round int to nearest round_to
def round_to_nearest_x(n , round_to=10):
return round(n / round_to) * round_to
|
0