开发者

JavaScript: Rounding question

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'.


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


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?


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;


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 <.


Or for the mathematically inclined :)

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

50 is (mathematically correctly) rounded up to 100.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜