Question

Lets say I have two vars called value1 and value2. These values would be input by the user but lets just pretend they did already and these are the values

    var value1 = 5;
    var value2 = 7; 
    var comparison = .785  

I just want to compare the values plus or minus the comparison so when the code displays output it only displays the values of 5 + or - .785 and 7 + or minus .785

For some context the following code is a pulling information from a json object that has two separate lists of numbers lets say number1 and number2 and a ton of other info but dont worry about any of that, that all works fine

       $("#createlist").click(function() {
            var value1 = Number($("#value1").val());
            var value2 = Number($("#value2").val());    
            var comparison = .785

            $.getJSON("get_divvy_data.php", null, function(data) {
                var total_bikes_available = 0;
                $("#stationtable .stationrow").remove();
                $.each(data.stationBeanList, function(index, station) {

This next part is where I am having a problem with.

                  if( station.number1 is <= value1 + - comparison && station.number2 is <= value2 + - comparison) {
                       //do something
                   }

I just dont know how to write the if statement and comparison effectively.

Was it helpful?

Solution

One possible approach:

if (Math.abs(value1 - station.number1) <= comparison
    && Math.abs(value2 - station.number2) <= comparison) {
   //...    
}

... but be aware of possible edge cases caused by float-math imperfection. For example:

var value     = 0.9;
var reference = 0.7;
var delta     = 0.2;
console.log(value - reference <= delta); // false
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top