Does anyone know how to round up a number to its nearest multiple of 5? I found an algorithm to round it to the nearest multiple of 10 but I can\'t find this one.
T
To round to the nearest of any value
int round(double i, int v){
return Math.round(i/v) * v;
}
You can also replace Math.round()
with either Math.floor()
or Math.ceil()
to make it always round down or always round up.
In case you only need to round whole numbers you can use this function:
public static long roundTo(long value, long roundTo) {
if (roundTo <= 0) {
throw new IllegalArgumentException("Parameter 'roundTo' must be larger than 0");
}
long remainder = value % roundTo;
if (Math.abs(remainder) < (roundTo / 2d)) {
return value - remainder;
} else {
if (value > 0) {
return value + (roundTo - Math.abs(remainder));
} else {
return value - (roundTo - Math.abs(remainder));
}
}
}
The advantage is that it uses integer arithmetics and works even for large long numbers where the floating point division will cause you problems.
int roundUp(int n, int multipleOf)
{
int a = (n / multipleOf) * multipleOf;
int b = a + multipleOf;
return (n - a > b - n)? b : a;
}
source: https://www.geeksforgeeks.org/round-the-given-number-to-nearest-multiple-of-10/
This Kotlin function rounds a given value 'x' to the closest multiple of 'n'
fun roundXN(x: Long, n: Long): Long {
require(n > 0) { "n(${n}) is not greater than 0."}
return if (x >= 0)
((x + (n / 2.0)) / n).toLong() * n
else
((x - (n / 2.0)) / n).toLong() * n
}
fun main() {
println(roundXN(121,4))
}
Output: 120
You can use this method Math.round(38/5) * 5
to get multiple of 5
It can be replace with Math.ceil
or Math.floor
based on how you want to round off the number
int round(int num) {
int temp = num%5;
if (temp<3)
return num-temp;
else
return num+5-temp;
}