Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading