Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way of checking if a value is within a range and setting it's value if it falls outside of the range?

What I want to do is quite simple in itself, but I'm wondering is there is some really neat and compact way of accomplishing the same thing.

I have a float variable, and I want to check if it's value is between 0 and 1. If it's smaller than 0 I want to set it to zero, if it's larger than 1 I want to set it to 1.

Usually I do this:

// var myVar is set before by some calculation

if(myVar > 1){
    myVar = 1;
}
if(myVar < 0){ 
    myVar = 0;
}

Does anyone know of a more elegant/compact way of doing this?

like image 655
Asciiom Avatar asked Oct 12 '12 12:10

Asciiom


People also ask

How do you elegantly check if a number is within a range?

If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.

How do you elegantly check if a number is within a range Python?

You can check if a number is present or not present in a Python range() object. To check if given number is in a range, use Python if statement with in keyword as shown below. number in range() expression returns a boolean value: True if number is present in the range(), False if number is not present in the range.

How do you check if a value is within a range?

In Excel, to check if a value exists in a range or not, you can use the COUNTIF function, with the IF function. With COUNTIF you can check for the value and with IF, you can return a result value to show to the user. i.e., Yes or No, Found or Not Found.

How do you check if a value is within a range in Java?

ValueRange. of(minValue, maxValue); range. isValidIntValue(x); it returns true if minValue <= x <= MaxValue - i.e. within the range.

How do you check if a number is within a range in R?

The mutate() function from the dplyr package also allows us to check if a value is between a range. The dplyr mutate() function adds a column to our data frame specifying if the value is in range (TRUE) or not (FALSE).


2 Answers

One possible solution:

myVar = Math.min(1, Math.max(0, myVar));

Another:

myVar = myVar < 0 ? 0 : myVar > 1 ? 1 : myVar;
like image 149
Michal Klouda Avatar answered Oct 02 '22 00:10

Michal Klouda


Use Math.min and Math.max, and avoid having a condition.

var MAX = 100;
var MIN = 50;

var val = 75;
console.log( Math.max(MIN, Math.min(MAX, val)) );

var val = 49;
console.log( Math.max(MIN, Math.min(MAX, val)) );

var val = 101;
console.log( Math.max(MIN, Math.min(MAX, val)) );
like image 25
Louis Ricci Avatar answered Oct 02 '22 00:10

Louis Ricci