Reputation: 4482
Is there an idiomatic way to round to the nearest multiple of a number?
number multiple result
12.2 0.5 12.0
12.2 0.25 12.25
12.4 0.5 12.5
Upvotes: 7
Views: 1024
Reputation: 2162
You can define a function:
round_step(x, step) = round(x / step) * step
Usage:
julia> round_step(12.2, 0.25)
12.25
Such a function is actually used internally in Base for rounding numbers to a certain number of digits in a certain base:
julia> Base._round_step(12.2, 0.25, RoundNearest)
12.25
However since this is an internal implementation detail you shouldn't rely on this function. This function in turn calls _round_invstep
.
julia> Base._round_invstep(12.2, 4, RoundNearest)
12.25
julia> Base._round_invstep(12.4, 2, RoundNearest)
12.5
Which performs the operation round(x * invstep, r) / invstep
.
Because your examples happen to correspond to 0.1 in base 4 and base 2 you can also use round
directly for these particular cases:
julia> round(12.2; base=2, digits=1)
12.0
julia> round(12.2; base=4, digits=1)
12.25
julia> round(12.4; base=2, digits=1)
12.5
Upvotes: 12