Ideomatic way to get the closest multiple of .5 to...
# mathematics
s
Ideomatic way to get the closest multiple of .5 to a given float? E.g.
closest(1.03)=1.05
,
closest(1.02)=1.00
,
closest(1.05)=1.05
a
The only solution I see out of the box is multiply + round + divide. And it probably also will be the most effective one
So if you wont to round by 0.05 you need something like
round(d*20.0)/20.0
1
g
There are also another two solutions (to get closest to
a
multiple of
b
): 2.
a - a.IEEErem(b)
(
IEEErem
is from
kotlin.math
and iss available only for K/JVM and K/Native) 3.
(a + b/2).let { it - it.mod(b) }
In both cases we just subtract remainder of division of
a
by
b
to get product of the division's quotient and the divisor
b
.
s
Thank you so much both of you!!