Home > OS >  rounding up to the multiplier
rounding up to the multiplier

Time:01-24

I am writing a javascript code which gives output of a X which always divisible by Y

For example if I have 7 which is not divisible by 4 but I want the code to add number up to 8

This is the code I did, it works for 7, but it should work for value 8

var x = 7
var y = 4
x = x   (y - x%y)
console.log(x)

I get the output 8 which is correct, but

var x = 8
var y = 4
x = x   (y - x%y)
console.log(x)

I am getting 12 which is not correct, I want the same 8

My question is, without putting an if condition how I will make this formula work?

CodePudding user response:

If I understood correctly, you're probably looking for something like this:

Math.ceil(x / y) * y;

function toNearestMultiple(x, y) {
    return Math.ceil(x / y) * y;
}

console.log(toNearestMultiple(7, 4));
console.log(toNearestMultiple(8, 4));
console.log(toNearestMultiple(9, 4));

CodePudding user response:

This should also do it:

var x = 8
var y = 4
x = x y-(x-1)%y-1
console.log(x)

  • Related