I frequently find it useful to round to multiple of an integer, most commnly 5
, powers of 10
, and similar.
First, I usually use something like
round_to(n, x) = round(Int, x / n) * n
Is there a better implementation? Just being curious, this is not performance-critical.
Second, is there a package with this kind of functionality? If not, would it make sense to add to some existing package?
If you want to round up/down to powers of something, I’d use nextpow
and prevpow
respectively, see
help?> nextpow
search: nextpow nextprod
nextpow(a, x)
The smallest a^n not less than x, where n is a non-negative integer. a must
be greater than 1, and x must be greater than 0.
For a rounding to the nearest such power, a simple branch or if-else should work too.
There’s also nextprod
and prevprod
(mentioned in the docstring above) which might be useful in certain situations but generally I think your function should work well enough.
3 Likes