Round To Nearest X

Sometimes it is necessary to round a number to the nearest X (.1,5,10, etc). Below is some code to do that:
==PHP==
{{{ lang=php line=1
# 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==
{{{ lang=python line=1
# Round int to nearest round_to
def round_to_nearest_x(n , round_to=10):
return round(n / round_to) * round_to
}}}


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *