views:

116

answers:

5

If I have the following

var lowerBound = 0;
var higherBound = 100;
var inputVar = document.getElementById('input').value;  // e.g. 51

How do I programatically determine if the inputVar is closer to variable lowerBound or variable higherBound?

Meaning, if the user inputs '51', the function should return '100'. But if the user inputs '49', it should return '0'.

A: 

Why not find the difference between lower and upper and then:

inputVar = document.getElementById('input').value < middleVal ? lowerBound : upperBound.

The only problem then is, what is the value of 50?

James Black
A: 

You will have to decide whether you want a value of 50 to match the lower or upper bound yourself:

var inputVar = parseFloat(document.getElementById('input').value);
inputVar = (inputVar > 50) ? higherBound : lowerBound;
cballou
A: 

This should do what you want:

var inputVar = parseInt(document.getElementById('input').value, 10);
var rounded = (higherBound - inputVar) <= (inputVar - lowerBound) ? higherBound : lowerBound;

If you want 50 to round down to 0, then change <= to <.

Phil Ross
+1  A: 

Find the middle value for the upper and lower bounds then test.

function findNearest(num) {
 if((num - 0) !== num) throw "invalid test value";
 var lower = 0;
 var upper = 100;
 var middle = ( upper - lower ) / 2;
 return ( num > middle ? upper : lower );
}

findNearest(2); // lower
findNearest(15.465); // lower
findNearest(50); // lower
findNearest(51); // upper
findNearest(122); // upper
findNearest('asdasd'); // exception
findNearest(null); // exception
Jonathan
A: 

Or for the mathematically inclined :)

var rounded = Math.round(inputVar / 100) * 100;

50 is (mathematically correctly) rounded up to 100.

bmoeskau
What about varying boundaries?
Crescent Fresh
OK, if you want to be a stickler: Math.round((Math.max(0,inputVar) % 100) / 100) * 100;
bmoeskau