Advanced Rounding

A more advanced rounding function. Allows for rounding to the nearest 10, for example.

HTML

<div class="foo">Wiggle your mouse here!</div>

CSS

* { box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box; }
html,body { height: 100%; padding:0;margin:0;}
.foo { padding: 2em; font-size:2em;width: 100%; height: 100%;background-color: #f90; color: #fff; }

JavaScript

function nearest(num,factor) {
    if(typeof factor !== 'number') {
        factor = 1;
    }
    
    if(num===factor) {
        return num; //guard
    } else {
        var result;
        var upperBound=0;
        var lowerBound=0;

        if(num<0) {
            while(upperBound>num) {
                upperBound -= factor;
            }
            
            if(upperBound==num){
                result = upperBound;
            } else {
                lowerBound = upperBound+factor;
                if(num-lowerBound > upperBound-num) {
                    result = lowerBound;
                } else {
                    result = upperBound;   
                }
            }
        } else if(num>0) {
            while(upperBound<num) {
                upperBound += factor;
            }
            
            if(upperBound==num){
                result = upperBound;
            } else {
                lowerBound = upperBound-factor;
    
                if(num-lowerBound < upperBound-num) {
                    result = lowerBound;
                } else {
                    result = upperBound;   
                }
            }
        } else {
            result = 0;
        }

        return result;
    }
}

//This example would calculate the mouse's nearest intersection on a 40px grid.
$(document).on('mousemove', function(e) {
    x = nearest(event.pageX,40);
    y = nearest(event.pageY,40);
    $('.foo').text(x+','+y);
});