maudulus maudulus - 1 year ago 68
Javascript Question

How to round to a multiple of a specific number JavaScript?

I need to round a number to the nearest multiple of 27 with JavaScript. It would be better if I could always round UP to the number, but it would also be useful to know how to round to the closest multiple of 27 (whether up or down). It doesn't have to be vanilla JavaScript it could be jQuery too.

Answer Source

Divide the number by 27, round (or .ceil to round it up) the result and multiply by 27:

var x = 28;
console.log('round', Math.round(x/27) * 27);
console.log('ceil', Math.ceil(x/27) * 27);

var y = 47;
console.log('round', Math.ceil(y/27) * 27);
console.log('ceil', Math.round(y/27) * 27);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download