Dyck
Dyck

Reputation: 2675

How to check if a number is between two values?

In JavaScript, I'm telling the browser to do something if the window size is greater than 500px. I do it like so:

if (windowsize > 500) {
    // do this
}

This works great, but I would like to apply this same method, but with a range of numbers. So I would like to tell my browser to do stuff if the window size is between 500px and 600px. I know this wouldn't work, but here is how I imagined it:

if (windowsize > 500-600) {
    // do this
}

Is this even possible, within JavaScript?

Upvotes: 204

Views: 598243

Answers (11)

David Thomas
David Thomas

Reputation: 253308

I had a moment, so, although you've already accepted an answer, I thought I'd contribute the following:

Number.prototype.between = function(a, b) {
  var min = Math.min(a, b),
    max = Math.max(a, b);

  return this > min && this < max;
};

var windowSize = 550;

console.log(windowSize.between(500, 600));

JS Fiddle demo.

Or, if you'd prefer to have the option to check a number is in the defined range including the end-points:

Number.prototype.between = function(a, b, inclusive) {
  var min = Math.min(a, b),
    max = Math.max(a, b);

  return inclusive ? this >= min && this <= max : this > min && this < max;
}

var windowSize = 500;

console.log(windowSize.between(500, 603, true));

JS Fiddle demo.

References:

Upvotes: 156

Isaac Vega
Isaac Vega

Reputation: 330

I know there's an accepted answer, but I want to provide some ways that can be useful in certain scenarios. If we want to check whether n is between x and y, we can do:

x <= n && n <= y
(x - n) * (y - n) <= 0

The second one is very useful when you're trying to get the same result even if you swap x and y.

Upvotes: 7

mojaba moradi
mojaba moradi

Reputation: 131

  function handleBetween(number, calc) {
        let [a, b] = calc;
        let min = Math.min(a, b), max = Math.max(a, b);
        return number > min && number < max;
    }

    if(510 >500 && 510 <600){
    console.log(`510 >500 && 510 <600 is true`)
    }


    if(610 >500 && 610 <600){
    // false
    console.log(`610 >500 && 610 <600 is true`)
    } else console.log(`610 >500 && 610 <600 is false`)


    
     console.log(handleBetween(510, [500, 600])); // true
     console.log(handleBetween(610, [500, 600])); // false

Upvotes: 0

Eliav Louski
Eliav Louski

Reputation: 5214

just like David answer but i needed inclusive for either a or b. so my sol:

export const between = (num: number, a: number, b: number, inclusiveA = true, inclusiveB = true): boolean => {
  if (a > b) [a, b, inclusiveA, inclusiveB] = [b, a, inclusiveB, inclusiveA];
  if (a == b && (inclusiveA || inclusiveB)) [inclusiveA, inclusiveB] = [true, true];
  return (inclusiveA ? num >= a : num > a) && (inclusiveB ? num <= b : num < b);
};

if (require.main === module) {
  console.log(between(12, 15, 10)); //true
  console.log(between(15, 15, 10)); //true
  console.log(between(15, 10, 15)); //true
  console.log(between(10, 10, 15, false)); //false
  console.log(between(15, 10, 10, true, false)); //false
  
  //edge case: if a==b then enough that either of the edges is inclusive
  console.log(between(10, 10, 10, true, false)); //true
}

its also typescript and not javascript

Upvotes: 0

Fahd Allebdi
Fahd Allebdi

Reputation: 404

this is a generic method, you can use everywhere

const isBetween = (num1,num2,value) => value > num1 && value < num2 

Upvotes: 7

yukashima huksay
yukashima huksay

Reputation: 6238

Here is the shortest method possible:

if (Math.abs(v-550)<50) console.log('short')
if ((v-500)*(v-600)<0) console.log('short')

Parametrized:

if (Math.abs(v-max+v-min)<max+min) console.log('short')
if ((v-min)*(v-max)<0) console.log('short')

You can divide both sides by 2 if you don't understand how the first one works;)

Upvotes: 4

Hanzla Habib
Hanzla Habib

Reputation: 3703

You can use Multiple clause in if condition instead of writing

if (windowsize > 500-600) {
    // do this
}

because this really makes no sense logically JavaScript will read your if condition like

windowSize > -100 

because it calculates 500-600 to -100

You should use && for strict checking both cases for example which will look like this

if( windowSize > 500 && windowSize < 600 ){

// Then doo something

}

Upvotes: 4

gorodezkiy
gorodezkiy

Reputation: 3419

It's an old question, however might be useful for someone like me.

lodash has _.inRange() function https://lodash.com/docs/4.17.4#inRange

Example:

_.inRange(3, 2, 4);
// => true

Please note that this method utilizes the Lodash utility library, and requires access to an installed version of Lodash.

Upvotes: 38

Ram
Ram

Reputation: 144669

Tests whether windowsize is greater than 500 and lesser than 600 meaning that neither values 500 or 600 itself will result in the condition becoming true.

if (windowsize > 500 && windowsize < 600) {
  // ...
}

Upvotes: 306

WiseGuy
WiseGuy

Reputation: 429

I just implemented this bit of jQuery to show and hide bootstrap modal values. Different fields are displayed based on the value range of a users textbox entry.

$(document).ready(function () {
    jQuery.noConflict();
    var Ammount = document.getElementById('Ammount');

    $("#addtocart").click(function () {

            if ($(Ammount).val() >= 250 && $(Ammount).val() <= 499) {
                {
                    $('#myModal').modal();
                    $("#myModalLabelbronze").show();
                    $("#myModalLabelsilver").hide();
                    $("#myModalLabelgold").hide();
                    $("#myModalPbronze").show();
                    $("#myModalPSilver").hide();
                    $("#myModalPGold").hide();
                }
            }
    });

Upvotes: 0

David
David

Reputation: 1927

I prefer to put the variable on the inside to give an extra hint that the code is validating my variable is between a range values

if (500 < size && size < 600) { doStuff(); }

Upvotes: 119

Related Questions