How to Round Numbers To Arbitrary Values

This is just a quick little function I find pretty useful. It allows you to round any number to an arbitrary value, and can be useful for when you’re working with and rendering to a grid or want a slider that increments by a certain step.

if(typeof Math.roundTo === "undefined") {
Math.roundTo = function(num, step) {
return Math.floor((num / step) + .5) * step;
Math.roundTo(15, 10); // >> 20
Math.roundTo(14.99, 10); // >> 10
Math.roundTo(42, 1); // >> 42

As you can see, it’s pretty straightforward. Just pass in the number you want to round, and the step you want it rounded to and voilá, you’re good to go.

One thought on “How to Round Numbers To Arbitrary Values”

  1. Kronberg says:

    Thanks, just want I was looking for.Keep up the good work. I found a lot of nice tips and tricks.