rounding up to the multiplier

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?

>Solution :

This should also do it:

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

Leave a Reply